简体   繁体   English

PHP jQuery json_encode

[英]PHP jQuery json_encode

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的值?

If you set datatype: "json" in the .ajax() call, the data object you get, contains the already parsed JSON. 如果在.ajax()调用中设置datatype: "json" ,则获得的data对象包含已经解析的JSON。 So you can access it like any other JavaScript object. 因此,您可以像任何其他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脚本中将执行脚本,其他任何东西将是以字符串形式返回)。

1) 1)

console.log(data[0].response)

2) 2)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM