PHPリクエストでJSON文字列をJSONオブジェクトに変換する方法と初心者がよく遭遇する問題解決

1147 ワード

//ほとんどのインタフェースで得られるデータはjson//なので、私たちがデータを受け取る最初の操作は一般的にJSONです.parse()/JSONをparse操作は関数に配置されます
//             json      json  
function getJSON(url,callback,error){
  //                              
  //             
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.status === 200){
      callback && callback(JSON.parse(xhr.responseText));
      //        JSON   
    }else if(xhr.readyState === 4 && xhr.status === 404){
      error && error(xhr.statusText);//     status     
    }
  }
  xhr.open('GET',url,true);
  xhr.send();
}
getJSON('url',function(data){
  //  getJSON   ,            ,    data        
  //           JSON  ,        JSON.parse(xhr.responseText);

},function(errorText){
  alert(errorText);
  //errorText      
})

      ,  xhr.responseText    xhr.responseXML   :         XML           

       JSON.parse     JSON     JSON       
{
  "name" : "  ";
}

         php          Unexpected token < in JSON at position 0
     JSON.parse          
        ,            ,          。