PHP jQuery json_encode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18874581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:21:39  来源:igfitidea点击:

PHP jQuery json_encode

phpjqueryjson

提问by ngplayground

PHP

PHP

$results[] = array(
    'response' => $response
);
echo json_encode($results);

Using the above returns to my jQuery the following data

使用上述返回到我的 jQuery 以下 data

Part of .ajax()

.ajax() 的一部分

success:function(data){
    console.log(data);
}

Outputs

输出

 [{"response":0}]

How could I change console.log(data)to pick the value of response?

我怎么能改变console.log(data)选择的值response

回答by Sirko

If you set datatype: "json"in the .ajax()call, the dataobject you get, contains the already parsed JSON. So you can access it like any other JavaScript object.

如果您datatype: "json".ajax()调用中设置,data您获得的对象将包含已解析的 JSON。因此您可以像访问任何其他 JavaScript 对象一样访问它。

console.log( data[0].response );

Otherwise you might have to parse it first. ( This can happen, when the returned MIME type is wrong.)

否则,您可能必须先解析它。(当返回的 MIME 类型错误时,可能会发生这种情况。)

data = JSON.parse( data );
console.log( data[0].response );

Citing the respective part of the jQuery documentation:

引用jQuery 文档的相应部分:

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).

数据类型

如果没有指定,jQuery 将尝试根据响应的 MIME 类型推断它(XML MIME 类型将产生 XML,在 1.4 中 JSON 将产生一个 JavaScript 对象,在 1.4 脚本中将执行脚本,其他任何类型都将以字符串形式返回)。

回答by Falci

1)

1)

console.log(data[0].response)

2)

2)

for(var i in data){
  console.log(data[i].response);
}

回答by ngplayground

success:function(data){
    data = $.parseJSON(data);
    console.log(data[0].response);
}