[英]How to read JSON response with jQuery
I am trying to read response with jQuery and I have no idea how it works with response. 我正在尝试使用jQuery读取响应,但我不知道它如何与响应一起工作。
See the small example code with js post + response here: 在此处查看带有js post + response的小示例代码:
$.ajax({
url: "http://localhost/ajaxpost/ajax.php",
type: "post",
data: "action=check&uid=1",
dataType: "json",
success: function(data){
$("#result").html('submitted successfully');
response = JSON.parse(data);
status = response.status;
alert(status);
},
error:function(){
$("#result").html('there is error while submit');
}
});
Response is: 响应是:
{"first":"John","last":"Heyden","uid":"1","token":"10","value":"100000","friends":"23","country":"australia","status":"online"}
Now what I want in this is to alert online
现在我想要的是
alert online
Can someone tell me what I am missing in this? 有人可以告诉我我在这方面缺少什么吗?
When I remove dataType: "json", this works fine 当我删除dataType:“ json”时,这工作正常
success: function(data){
$("#result").html('submitted successfully');
var r = jQuery.parseJSON(data);
alert(r.status);
There is no need to parse response as the dataType is set as json, the method will parse the response to json ans will pass it to the handler 由于dataType设置为json,因此无需解析响应,该方法将解析对json的响应,并将其传递给处理程序
just 只是
alert(data.status)
Ex: 例如:
$.ajax({
url: "http://localhost/ajaxpost/ajax.php",
type: "post",
data: "action=check&uid=1",
dataType: "json",
success: function(data){
$("#result").html('submitted successfully');
status = data.status;
alert(status);
},
error:function(){
$("#result").html('there is error while submit');
}
});
做就是了
alert(data.status); // online
Not sure about your parsing method there. 不确定那里的解析方法。 Since you're using jQuery, try:
由于您使用的是jQuery,请尝试:
var r = jQuery.parseJSON(data);
alert(r.status);
Since you defined the dataType
as json you don't need to parse it, it will be converted to object for you, so just do: 由于您将
dataType
定义为json,因此您无需解析它,它将为您转换为object,所以只需执行以下操作:
$.ajax({
url: "http://localhost/ajaxpost/ajax.php",
type: "post",
data: "action=check&uid=1",
dataType: "json",
success: function(data){
$("#result").html('submitted successfully');
//Don't need this line
//response = JSON.parse(data);
//you called the object data, so use it
status = data.status;
alert(status);
},
error:function(){
$("#result").html('there is error while submit');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.