Javascript 如何获得;“数据”;来自xhr.responseText的字段?

Javascript 如何获得;“数据”;来自xhr.responseText的字段?,javascript,jquery,xmlhttprequest,Javascript,Jquery,Xmlhttprequest,我有下面给出的XMLHttpRequest()函数 var searchFriendRequests = function (userid) { var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:6344/api/Registeration/searchFriendrequests?userid=' + userid, false); xhr.setRequestHeader("Conten

我有下面给出的
XMLHttpRequest()
函数

var searchFriendRequests = function (userid) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:6344/api/Registeration/searchFriendrequests?userid=' + userid, false);
    xhr.setRequestHeader("Content-Type", "text/xml");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                var data = xhr.responseText;
            }
        }
    };
    xhr.send(null);
}
其中
xhr.responseText
将值返回为

{
    "$id": "1",
    "ContentEncoding": null,
    "ContentType": null,
    "Data": [
        {
            "$id": "2",
            "email": "anu@gmail.com"
        },
        {
            "$id": "3",
            "email": "anu@gmail.com"
        }
    ],
    "JsonRequestBehavior": 1,
    "MaxJsonLength": null,
    "RecursionLimit": null
}

如何从
responseText
中获取
数据
字段?

您首先需要用JSON解析responseText,为此您应该使用。然后您可以使用密钥访问它

var json = JSON.parse(xhr.responseText);
var yourData = json.Data; // or json["Data"]
使用,例如:


要简单地从
数据
对象获取电子邮件或任何其他字段,请使用以下命令:

data.Data[0].email

应该首先解析对json对象的响应,然后从响应中获取数据字段

var responseText = JSON.parse(xhr.responseText),
     data = responseText.Data;

现在,您可以使用:

xhr.responseJSON

不需要任何解析。希望它对您提出ajax请求时有所帮助,您可以提供:

当您收到回复时,对于此类请求:

如果指定了
json
,则在将响应作为对象传递给成功处理程序之前,将使用
jQuery.parseJSON
解析响应。解析后的JSON对象通过
jqXHR
对象的
responseJSON
属性提供

您可以通过以下方式访问数据:

var data =  xhr.responseJSON
完整示例:

  $ajax.({
    dataType: 'json',
    success: function( xhr ) {
      var yourData =  xhr.responseJSON;
      console.log( yourData );
    },
  });
请只回答您的代码以添加信息。请添加解释,这将有助于消除StackOverflow是免费代码编写服务的误解。
var data =  xhr.responseJSON
  $ajax.({
    dataType: 'json',
    success: function( xhr ) {
      var yourData =  xhr.responseJSON;
      console.log( yourData );
    },
  });
var jsonResponse = JSON.parse(xhr.responseText);
console.log(jsonResponse);