简体   繁体   English

如何将该Json数组转换为JQuery可读的格式?

[英]How can I convert this Json array to a format readable by JQuery?

Bit of a vague question, but I'm unsure how I can this to work. 有点模糊的问题,但是我不确定如何使它起作用。 Firebug says the Json object (array?) from my ajax request looks like: Firebug说我的ajax请求中的Json对象(数组?)看起来像:

{
"jsonResult":
"[
   {\"OrderInList\":1},
   {\"OrderInList\":2}
]"
}

This is retrieved through through a $.getJSON ajax request: 这是通过$ .getJSON ajax请求检索的:

    $.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, testData, function (jsonResult) {
        $('#orderInList option').remove();

        var map = {
            "TestKey1": "TestValue1",
            "TestKey2": "TestValue2"
        };

        $.each(jsonResult, function (key, value) {
            $("#orderInList").append($("<option value=" + key + ">" + value + "</option>")
            );
        });

If I replace $.each(jsonResult) with $.each(map) the select list populates correctly. 如果我将$ .each(jsonResult)替换为$ .each(map),则选择列表将正确填充。 Otherwise my select list just says 'undefined'. 否则,我的选择列表只会显示“未定义”。

I serialize the Json in this Action in my MVC Controller: 我在MVC控制器的此Action中序列化了Json:

    public JsonResult GetOrderSelectList(int parentCategoryId)
    {
        var result = Session
            .QueryOver<Category>()
            .Where(x => x.Parent.Id == parentCategoryId)
            .OrderBy(x => x.OrderInList).Asc
           .List();

        var toSerialize =
            result.Select(r => new {r.OrderInList});

        var jsonResult = JsonConvert.SerializeObject(toSerialize);                             
        return Json(new
                        { jsonResult,
                        }, JsonRequestBehavior.AllowGet);

    }

So I think the problem might be the format of Json the Action is responding with? 所以我认为问题可能出在Action响应的Json格式上? Any help appreciated! 任何帮助表示赞赏!

Edit for answer 编辑答案

Both of the answers below helped me. 以下两个答案都帮助了我。 I couldn't seem to strongly type the variable jsonResult so thanks @JBabey for pointing out my error in reading the json property, and suggesting function (key, value) in the $.each statement. 我似乎无法强烈键入变量jsonResult,因此感谢@JBabey指出我在读取json属性时出错,并在$ .each语句中建议了函数(键,值)。

Thanks @Darin Dimitrov for helping sort my controller out! 感谢@Darin Dimitrov帮助我整理控制器!

Your controller action is wrong. 您的控制器操作错误。 You are manually JSON serializing inside it and then returning this as a JSON result thus ending up with a double JSON serialization. 您正在其中手动进行JSON序列化,然后将其作为JSON结果返回,从而以双JSON序列化结束。 You could directly return the array and leave the JSON serialization plumbing to the ASP.NET MVC framework: 您可以直接返回数组,并将JSON序列化管道留给ASP.NET MVC框架:

public ActionResult GetOrderSelectList(int parentCategoryId)
{
    var result = Session
        .QueryOver<Category>()
        .Where(x => x.Parent.Id == parentCategoryId)
        .OrderBy(x => x.OrderInList)
        .Asc
        .List();
    return Json(result, JsonRequestBehavior.AllowGet);
}

and then: 接着:

$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, testData, function (jsonResult) {
    $('#orderInList option').remove();
    $.each(jsonResult, function () {
        $('#orderInList').append(
            $("<option value=" + this.Id + ">" + this.Value + "</option>")
        );
    });
});

Notice that I am using this.Id and this.Value here. 请注意,我在这里使用this.Idthis.Value This assumes that the JSON result looks like this: 假设JSON结果如下所示:

[{"Id": 1, "Value": "some value"}, {"Id": 2, "Value": "some other value"}]

You will have to adapt those property names based on your actual Category model. 您将不得不根据您的实际“ Category模型调整这些属性名称。

You are confusing a property of your data returned by your ajax with the data itself. 您正在将ajax返回的数据的属性与数据本身混淆。 $.each will work fine if you correct this. 如果您更正此错误,则$.each将正常工作。

Your data returned looks like this: 您返回的数据如下所示:

{
    "jsonResult": "[
        {\"OrderInList\":1},
        {\"OrderInList\":2}
    ]"
}

Which means that is the object passed to your success function. 这意味着该对象是传递给您的成功函数的对象。 Call it data instead of jsonResult . 将其jsonResult data而不是jsonResult

function (data) {
    ...
    $.each(data.jsonResult, function (key, value) {
        ...
    });
});

Also, your array is coming through as a string, so you may need to parse it before $.each will be able to iterate it. 另外,您的数组将作为字符串传递,因此您可能需要先解析它,然后$.each才能对其进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM