PHP jQuery json_encode

标签 php jquery json

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/

相关文章:

javascript - 二维数组仅在以 [0][x] 开头时有效

.net - 如何从 PHP 使用 WCF Web 服务?

php - 如何使用警报 View 单击按钮来更新 sql 中的值?

php - 在 php 中使用 curl 进行重定向

javascript - jQuery:新的临时 DOM 元素的内存管理

jquery - jQuery 的 space 和 > 选择器有什么区别?

javascript - DB 和 D3 通过 php 连接。无法完成 D3noob 的教程

PHP 从 HTML 表单插入/更新 mysql 表

javascript - 如何评估 JSON 的键以匹配特定键并提取该键的值?

c# - 为 JSON 对象数组命名