从ajax成功函数访问Json对象

时间:2014-08-26 10:24:17

标签: javascript ajax json

这是我在控制器中的JSON对象,我需要从ajax成功函数访问这个对象,

 $.ajax({
     url: "@Url.Action("Temp","GRN")",
     type: "POST",
     data: { term: request.term },
     dataType: "json",
     success: function (data) {
       alert(data.msg);
     }
 });

这是我在控制器中的json

var Item = new[]
        {
        new  { Item_Name = "Soap", Item_Code = "IT1", Purchase_Price = 10.00, Sell_Price = 20.50},
        new  { Item_Name = "Pen", Item_Code = "IT2", Purchase_Price = 20.00, Sell_Price = 30.00},
        new  { Item_Name = "Paper", Item_Code = "IT3", Purchase_Price = 30.00, Sell_Price = 40.00},
        new  { Item_Name = "Brush", Item_Code = "IT4", Purchase_Price = 40.00, Sell_Price = 50.00}
        };

        return Json(Item);

3 个答案:

答案 0 :(得分:3)

JSON对象是传递给data函数的success

您正在警告data.msg未定义的内容,因此您可能会在警报中获得undefined

答案 1 :(得分:2)

看起来像一个数组,所以你可能想要迭代结果:

success: function (data) {
    $.each(data, function(i, item){
        console.log(item, item.Item_Name); //etc...
    });
}

答案 2 :(得分:2)

data是您的json

data[0].Item_Name //  "Soap"
data[0].Item_Code  // "IT1"
data[1].Item_Name // "Pen"

您可以使用以下简单的方法迭代数据数组:

for(var i = 0 ; i < data.length ; i++)
{
    var curr = data[i];
    curr.Item_Name; // 
}