如何使用jquery从json编码数据中选择一个值?

时间:2015-09-18 06:41:45

标签: jquery json

jquery代码:

   function getWriterBookName(url, data) {
    $.ajax({
        type: 'POST',
        url: url,
        data: data, //'foo='+ bar+'&calibri='+ nolibri,
        success: function (msg) {
            console.log(msg);

            console.log(msg.Product.name);
        }
    });
}
$(document).ready(function () {
    // Edit product info
    var url = 'loadbookWriter';
    $(".startLoading").on("change", function () {
        var pid = $(this).val();
        alert(pid);
        var data = 'id=' + pid;// +'&calibri=' + 'nolibri';
        getWriterBookName(url, data);
    });
    // End edit product info

});

的console.log(MSG);提供以下控制台输出:

{"Product":{"id":"3","category_id":"2","name":"C","writer":"Santo","created":"2015-09-17 19:30:11"}}

我想拿起名字和作家的价值。我试试这个:

console.log(msg.Product.name);

但它不起作用。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

您错过的是dataType

$.ajax({
    type: 'POST',
    url: url,
    dataType:'json', //<-----add this.
    data: data, //'foo='+ bar+'&calibri='+ nolibri,
    success: function (msg) {
        console.log(msg);

        console.log(msg.Product.name);
    }
});

因此,当您的源返回json时错过dataType:"json",那么它将被视为jsonstring而不是有效的json。

所以,要么使用dataType:"json",要么在成功回调中使用它将其解析为JSON.parse()的有效json:

success: function (data) {
    var msg = JSON.parse(data); // <-----parse it if you don't have datatype set.
    console.log(msg.Product.name);
}

答案 1 :(得分:0)

试试这个:

var msg= {"Product":{"id":"4","category_id":"1","name":"C","writer":"santo","created":"2015-09-17 19:32:01"}}

$(document).ready(function(){
    alert("Name :" +msg.Product.name +", <br/>Writer:"+msg.Product.writer);
});