代码之家  ›  专栏  ›  技术社区  ›  James Cadd

读取json数据返回jQuery

  •  3
  • James Cadd  · 技术社区  · 14 年前

    我使用以下代码获取一些json格式的数据:

    $.ajax({
                type: "GET",
                url: "MyService.svc/GetSomeData",
                dataType: "text",
                success: function (data, textStatus) {
    
                    alert("Test: " + data.toString());
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert("Error: " + (errorThrown ? errorThrown : xhr.status));
                }
            });
    

    数据已成功返回到此调用,如下所示:

    {"d":"test data"}
    

    var myData = data["d"];
    

    然而,这似乎总是返回“未定义”。获取单个数据字符串“test data”缺少什么?

    3 回复  |  直到 14 年前
        1
  •  5
  •   Amir Ismail    12 年前

    data.d ?

        2
  •  8
  •   Sean Vieira    14 年前

    改变 dataType: "text", dataType: "json",

    您遇到的问题是,虽然返回的字符串实际上是有效的JSON,但它将作为字符串返回给success函数。字符串没有名为 d . 您需要做的是将JSON转换成一个javascript对象——如果您告诉jQuery您需要JSON,jQuery将为您做这件事。

        3
  •  0
  •   Drew Wills    14 年前

    我认为肖恩和;Thiago是正确的:使用 {dataType: "json"} (在$.ajax()的选项中)并使用 data.d