2016-07-05 124 views
1

如何获取JavaScript中的json数据?Javascript - 无法解析通过PHP发送的JSON或字符串

$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 

所以当JavaScript调用一个PHP的方法,其未能为可读格式解码:

$.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++ } 

}); 

输出:阵列

+0

你试过序列化的数据? – atoms

+0

你是什么意思?它是不是已经序列化了?而在php上使用json_decode? – YumYumYum

+0

使用'json_encode()'从PHP数组中生成JSON字符串,而不是'json_decode()'。 – Simba

回答

3

如果你得到来自卷边一个JSON编码字符串回复你不需要拨打json_decode就可以了,只需要回显字符串。 json_decode会将它转换成一个不是你想要的PHP数组。

此外,您应该使用$.getJSON调用您自己的端点,因为这会将JSON转换为您可以自动使用javascript的对象。

+0

谢谢你的工作。 – YumYumYum

2

您想要检索JSON数据,但是您对所需的数据使用json_decode() - 这会将JSON数据转换为PHP数组。不要这样做!

,你不解析JavaScript函数中的JSON,所以JS不能理解响应作为JSON对象 - 它只是一个字符串。

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...  
}); 
+0

谢谢,你的答案解决了这个问题。 – YumYumYum

+0

@YumYumYum没问题的队友,很高兴我能帮上忙。祝你好运 – Ben