[英]HOW to Parse JSON response from the server after AJAX POST-request?
正如您从标题中看到的问题。 这是我的工作:
发送类似的请求
$.ajax({
type: "POST",
url: "http://www.example.com/api/",
data: {
'data': '1',
'beacon': 'fried'
},
complete: function(res) {
//need help here...
}
});
API会回显。 如果我这样做document.forms["myform"].submit();
页面显示JSON响应,例如
{
"data": [{
"Chief": "Max",
"temperature": "65",
"done": "yes",
"cost": 24
}]
}
那么我应该如何解析(检查,显示值)? 尝试了很多方法。
任何帮助,将不胜感激 !
使用jquery-3.2.1.min.js的PS
您可以在request属性中将dataType设置为JSON:
$.ajax({
type: "POST",
url: "http://www.example.com/api/",
data: {'data': '1', 'beacon': 'fried'},
dataType: 'JSON',
complete: function (res) {
console.log(res); // will be decoded
// acces your values like this :
var data = res.responceText.data[0];
alert(data.Chief);
}
});
编辑
添加了如何访问特定数据。
你应该使用
JSON.parse()
由于您在json数据中包含数组,因此可以将其作为res.data [0] .cost或res.data [0] [“ cost”]访问
如果需要,请使用JSON.parse()
,否则您可以从res.data
获取数组
试试JSON.parse()
$.ajax({
type: "POST",
url: "http://www.example.com/api/",
data: {'data': '1', 'beacon': 'fried'},
complete: function (res) {
var arr = JSON.parse(res).data;
arr.forEach(function(obj) {
var cost = obj.cost || null,
Chief = obj.Chief || null,
temperature = obj.temperature || null,
done = obj.done || null;
console.log('Cost: ' + cost + ', Chief: ' + Chief + ', Temperature:' + temperature + ', Done: ' + done);
});
}
});
您可以使用JSON.parse()
$.ajax({
type: "POST",
url: "http://www.example.com/api/",
data: {'data': '1', 'beacon': 'fried'},
complete: function (res) {
var response = JSON.parse(res);
}
});
好吧,第一个问题是它不允许响应来自不同的域,因此我将所有代码转移到api所在的同一服务器上。
现在这段代码可以工作了:
$.ajax({
type: "POST",
url: "../api/",
data: {'data': '1', 'beacon': 'fried'},
dataType: 'JSON',
complete: function (res) {
console.log(res);
var r = JSON.parse(res.responseText);
console.log(r.data[0].Chief); //retrieved Alex, that is response from the server
}
});
谢谢大家!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.