PHP
$results[] = array(
'response' => $response
);
echo json_encode($results);
使用上面的代码将以下数据
返回到我的jQuery
.ajax() 的一部分
success:function(data){
console.log(data);
}
输出
[{"response":0}]
如何更改 console.log(data)
来选择 response
的值?
最佳答案
如果您在.ajax()
中设置数据类型:“json”
调用时,您获得的 data
对象包含已解析的 JSON。因此您可以像访问任何其他 JavaScript 对象一样访问它。
console.log( data[0].response );
否则你可能必须先解析它。 (当返回的 MIME 类型错误时,可能会发生这种情况。)
data = JSON.parse( data );
console.log( data[0].response );
引用 jQuery documentation 的相应部分:
dataType
If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
关于PHP jQuery json_encode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18874581/