如何使用jquery处理JSON?

rks*_*rst 6 asp.net-mvc jquery json

我有一个控制器,它返回JSON格式的自定义linq-to-sql模型对象列表到jquery ajax调用:

List<MyAppLibrary.Model.Search> listSearches = search.ToList();
        return new JsonResult { Data = listSearches };
Run Code Online (Sandbox Code Playgroud)

我有以下javascript获得响应:

$.getJSON("/ajax/getbrands",
    function(data) {
        alert(data);
    });
Run Code Online (Sandbox Code Playgroud)

我想知道如何在javascript中处理数据响应?如何获取Model.Search对象的Name参数?

谢谢.

Tim*_*ren 7

data从jQuery AJAX调用返回的变量包含JSON对象.您可以MyAppLibrary.Model.Search在JavaScript中访问每个对象的字段,如下所示:

// this will grab the Search object at index 0 of your list
// and put the Name property's value of the Search object
// into a var
var firstItemName = data.Data[0].Name;
Run Code Online (Sandbox Code Playgroud)


tva*_*son 6

data参数将有一个Data属性,它是你的列表Search模式.

 $.getJSON("/ajax/getbrands",
        function(data) {
             $.each(data.Data, function(i, item) {
                  // ... item will be a Search model...
                  // ... i will be the index of the item in the list...
                  // ...
             });
        }
 );
Run Code Online (Sandbox Code Playgroud)