从 ajax 读取值以 json 格式返回

Reading values from ajax return in json format

本文关键字:json 格式 返回 ajax 读取      更新时间:2023-09-26

在 ajax return 中,我得到 json 作为

[{"colourname":"red,yellow"}]

我想从 JSON 中获取"red,yellow"字符串,

阿贾克斯调用SE ,

$.ajax({
    type: "POST",
    url: "loadData.php",
    data: {
        productid: 'getId'
    }
}).done(function (msg) {
    alert('get ' + msg);
});

我试过了

msg[0].colourname  
msg["colourname"]

没有任何效果如何访问值?

$.ajaxdone 中返回的响应是原始字符串,而不是 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"] }

试试这个

$.ajax({
    type: "POST",
    url: "loadData.php",
    dataType: 'json'
    data: {
        productid: 'getId'
    }
}).done(function (msg) {
    alert('get ' + msg);
});
});