从jQuery AJAX请求中读取复杂的JSON对象

时间:2014-01-20 17:38:38

标签: jquery ajax json

我有一个Web服务,它返回一个JSON对象,我试图通过jQuery使用AJAX请求。这是电话:

function CallService() {
$.ajax({
    type: "GET",
    url: "/Home/CallJSON",
    dataType: "json",
    success: function (data) {
        alert(data["Data"]["?xml"].divisions.Section1[0].name);
        alert("Success");
    },
    error: function (data) {
        alert("Error" + data.responseText);
    }
});

}

以下是从Web服务请求收到的JSON输出:

{"ContentEncoding":null,"ContentType":null,"Data":"
{\"?xml\":
    {\"@version\":\"1.0\",\"@encoding\":\"utf-8\",\"@standalone\":\"yes\"},
    \"divisions\":
        {\"requestContact\":\"name@email.com, name2@email.com\",
        \"customize\":\"FOLDER1/FILE1.htm\",
        \"Section1\":[
            {\"@id\":\"1\",
            \"name\":\"Name Here\",
            \"Section2\":
                {\"@id\":\"1\",
                \"name\":\"Name Here2\",
                \"Section3\":
                    {\"@id\":\"1\",
                    \"name\":\"Name Here3\",
                    \"Section4\":[
                        {\"@id\":\"1\",
                        \"name\":\"Name Here4\",
                        \"#comment\":[],
                        \"display\":[
                            {\"@id\":\"1\",
                            \"name\":\"Display Name1\",
                            \"code\":\"500001\"},

                            {\"@id\":\"2\",
                            \"name\":\"Display Name2\",
                            \"code\":\"500023\"}
                        ]}
                    ]}
                }
            }]
        }
},
"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}

问题

我目前无法从JSON对象中提取任何内容。如果你查看我的ajax请求,如果我理解了这个JSON对象的结构,我相信我正在调用所有内容来从第一个“Section1”项中提取“name”元素:

data["Data"]["?xml"].divisions.Section1[0].name

但我不断得到错误:

  

未捕获的TypeError:无法读取未定义的属性“divisions”

显然,我在这里遗漏了一些东西。任何人?

修改 为了进一步解释,我正在访问一个我无法访问的Web服务。有权访问它的人通过在请求URL上添加“?type = json”作为参数来添加指定JSON请求的功能。我构建了一个中间Web服务,这是我的AJAX调用的本地服务,用于删除原本会出现的跨域问题。

这是我的中间后端网络服务:

    public JsonResult CallJSON()
    {
        string requestURL = "https://www.someurlhere.com/service.ashx?type=json";

        WebRequest webReq = WebRequest.Create(requestURL);
        webReq.Method = "GET";

        WebResponse webRes = webReq.GetResponse();
        Stream reqStream = webRes.GetResponseStream();
        StreamReader sr = new StreamReader(reqStream);
        string finalResponse = sr.ReadToEnd();

        JsonResult jsonResponse = new JsonResult();
        jsonResponse.Data = finalResponse;

        return Json(jsonResponse, JsonRequestBehavior.AllowGet);
    }

1 个答案:

答案 0 :(得分:2)

data.Data属性包含一个json字符串,您需要对其进行解码。

alert($.parseJSON(data["Data"])["?xml"].divisions.Section1[0].name)