dsbqfrr098575666
dsbqfrr098575666
2016-07-05 15:02

Javascript - 无法解析通过PHP发送的JSON或字符串

How do i get the json data in Javascript?

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$result=curl_exec ($ch); // it has json data 

curl_close ($ch);

/* PHP unit test - shows the data is available and it works 
$obj = json_decode($result, true);
foreach($obj as $k=>$v) {
  echo $k . ' ' . $v  . '<br/>';
}
*/

/* But, from PHP i need to send the data to Browser on Ajax/GET request*/
$obj = json_decode($result, true);
echo $obj;
//if i do not use json_decode and only do echo $result; then still
//javascript is unable to parse the json 

So when Javascript is calling that PHP method, its failing to decode as readable format:

$.get(submit_url + '/login?', {
  code_please: '007',
}, function(data_please) {

  // ------------------------------FAIL to READ 
  alert(data_please);
  alert(data_please[0]);
  alert(data_please.id);
  //var duce = jQuery.parseJSON(data_please);
  //var art1 = duce.email;
  //for(oooi in data_please.db) { data_please.db[oooi].id++ } 

});

Output: Array

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongxia19772008 dongxia19772008 5年前

    If your getting a JSON encoded string from the curl response you don't need to call json_decode on it, just echo the string out. json_decode will convert it into a PHP array which is not what you want.

    Also you should call your own endpoint using $.getJSON as this will convert the JSON into an object you can use with javascript automatically.

    点赞 评论 复制链接分享
  • duanjiu6697 duanjiu6697 5年前

    You want to retrieve JSON data, but you use json_decode() on the data you want - this turns the JSON data into a PHP array. Don't do that!

    Also, you're not parsing the JSON in the JavaScript function, so the JS can't understand the response as a JSON object - it's just a string.

    PHP:

    $result = curl_exec($ch); // it has json data 
    curl_close($ch);
    exit($result);
    

    JS:

    $.get(submit_url + '/login?', {
      code_please: '007',
    }, function(data_please) {
      var json = $.parseJSON(data_please);
    
      console.log(json);
      console.log(json[0]);
      console.log(json[0].id);
      //etc...      
    });
    
    点赞 评论 复制链接分享

相关推荐