无法读取Json Response

时间:2015-09-19 07:35:02

标签: jquery json ajax

我做了一个ajax调用,它在控制台中返回了{"SessionId":"1","UserName":"Bond","ReferrerUrl":"http://localhost:64132/Test.html","ResponseStatus":{}}之类的值。现在我想逐一阅读这个响应,我试图像下面的代码那样做..

$.ajax({
    type: 'POST',
    url: 'http://localhost:64132/Auth',
    data: JSON.stringify(UserDetails),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        console.log(data);
        debugger;
        $.each(data, function (idx, obj) {
            var UName = obj.UserName;
            console.log(UName);
        });
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

但在控制台中我收到undefined。请帮忙解决。感谢..

2 个答案:

答案 0 :(得分:1)

您需要使用 JSON.parse() $.parseJSON() 解析回复数据,也不需要 $.each()

$.ajax({
    type: 'POST',
    url: 'http://localhost:64132/Auth',
    data: JSON.stringify(UserDetails),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        data = JSON.parse(data);
        console.log(data);
        // parse json string
        debugger;
        var UName = data.UserName;
        console.log(UName);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

或者您需要在 $.ajax()

中设置响应数据类型
$.ajax({
    type: 'POST',
    url: 'http://localhost:64132/Auth',
    data: JSON.stringify(UserDetails),
    contentType: "application/json; charset=utf-8",
    dataType : 'json',
    // setting response datatype
    success: function (data) {
        console.log(data);
        // parse json string
        debugger;
        var UName = data.UserName;
        console.log(UName);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});

更新 如果您想迭代对象,则可以使用 $.each()

$.each(data, function (idx, val) {
    console.log(idx + ' : ' + val);
});

答案 1 :(得分:1)

  

但是在控制台中我得到了undefined

$.each()正在返回正确的结果idx将是UserName,或者属性名称obj将是对象的属性值



$.each({
  "SessionId": "1",
  "UserName": "Bond",
  "ReferrerUrl": "http://localhost:64132/Test.html",
  "ResponseStatus": {}
}, function(idx, obj) {
  console.log(idx, obj);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
&#13;
&#13;
&#13;