簡體   English   中英

如何將該Json數組轉換為JQuery可讀的格式?

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

有點模糊的問題,但是我不確定如何使它起作用。 Firebug說我的ajax請求中的Json對象(數組?)看起來像:

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

這是通過$ .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>")
            );
        });

如果我將$ .each(jsonResult)替換為$ .each(map),則選擇列表將正確填充。 否則,我的選擇列表只會顯示“未定義”。

我在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);

    }

所以我認為問題可能出在Action響應的Json格式上? 任何幫助表示贊賞!

編輯答案

以下兩個答案都幫助了我。 我似乎無法強烈鍵入變量jsonResult,因此感謝@JBabey指出我在讀取json屬性時出錯,並在$ .each語句中建議了函數(鍵,值)。

感謝@Darin Dimitrov幫助我整理控制器!

您的控制器操作錯誤。 您正在其中手動進行JSON序列化,然后將其作為JSON結果返回,從而以雙JSON序列化結束。 您可以直接返回數組,並將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);
}

接着:

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

請注意,我在這里使用this.Idthis.Value 假設JSON結果如下所示:

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

您將不得不根據您的實際“ Category模型調整這些屬性名稱。

您正在將ajax返回的數據的屬性與數據本身混淆。 如果您更正此錯誤,則$.each將正常工作。

您返回的數據如下所示:

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

這意味着該對象是傳遞給您的成功函數的對象。 將其jsonResult data而不是jsonResult

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

另外,您的數組將作為字符串傳遞,因此您可能需要先解析它,然后$.each才能對其進行迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM