我使用它接受JSON响应一个jquery Ajax调用:
VAR posturl ='/管理/ getparamdetails /';
VAR数据=adnetworkId =+ adnetworkId;
$阿贾克斯({
键入:POST,
网址:posturl,
数据:数据,
数据类型:JSON,
成功:函数(MSG){
//$("#displayPramForm").html(msg);
//alert('hello'+msg.length+''+ msg.hello.length);
执行console.log(味精);
如果(味精!='')
{
警报(msg.hello);
}
},
失败:功能(MSG){}
});
在我的PHP后台功能,我使用json_en code在一个简单的数组,如下所示:
$ json_en coded_string = json_en code(阵列(你好=>'ABC'));
回声$ json_en coded_string;
死;
但警报(msg.hello)返回未定义我。这是怎么回事错在这里? 此外,在我的的console.log 我能够得到的输出为:
{你好:ABC}
解决方案
使用 parseJSON
在返回数据:
如果(MSG){
味精= $ .parseJSON(MSG);
警报(msg.hello);
}
I am using a jquery ajax call which accepts json response :
var posturl = '/admin/getparamdetails/';
var data = "adnetworkId="+adnetworkId;
$.ajax({
type: "POST",
url: posturl,
data : data,
datatype: "json",
success: function(msg){
//$("#displayPramForm").html(msg);
//alert('hello'+msg.length+' '+msg.hello.length);
console.log(msg);
if(msg!='')
{
alert(msg.hello);
}
},
failure: function(msg){}
});
in my php backend function , I am using json_encode on a simple array as shown:
$json_encoded_string = json_encode(array("hello"=>'abc'));
echo $json_encoded_string;
die;
but alert(msg.hello) returns undefined for me. What is going wrong here ? Also , in my console.log I am able to get the output as :
{"hello":"abc"}
解决方案
Use parseJSON
on the return data:
if (msg) {
msg = $.parseJSON(msg);
alert(msg.hello);
}