在 ajax 返回中,我得到 json 作为
[{"colourname":"red,yellow"}]
我想从 json 中获取 "red,yellow"
字符串,
ajax 调用 se ,
$.ajax({
type: "POST",
url: "loadData.php",
data: {
productid: 'getId'
}
}).done(function (msg) {
alert('get ' + msg);
});
我试过了,
msg[0].colourname
msg["colourname"]
没有任何效果我如何访问值?
最佳答案
$.ajax
在 done
中返回的响应是原始字符串,而不是 JavaScript 对象。在 ajax 配置中设置 dataType: 'json'
,jQuery
会将 JSON msg
解析为 JavaScript 对象。
$.ajax({
type : "POST",
url : "loadData.php",
data : {
productid : 'getId'
},
dataType: 'json',
}).done(function(msg) {
alert('get '+msg);
});
如果您使用 Content-Type: application/json
发送服务器响应,则不需要显式设置 dataType
顺便说一句,您应该为 colourNames
使用数组:{"colournames":["red","yellow"] }
关于javascript - 从 ajax 读取值以 json 格式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19900504/