41

I have XMLHttpRequest() function given below

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);
}

where xhr.responseText returns value as

{
    "$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
}

How can I get the Data field from the responseText?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Midhuna
  • 4,523
  • 4
  • 21
  • 22

7 Answers7

61

use JSON.parse(), like:

var data=xhr.responseText;
var jsonResponse = JSON.parse(data);
console.log(jsonResponse["Data"]);
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
14

You first need to parse responseText in JSON, for this you should use JSON.parse(). Then you can access it using key.

var json = JSON.parse(xhr.responseText);
var yourData = json.Data; // or json["Data"]
Satpal
  • 132,252
  • 13
  • 159
  • 168
3

To simply get the email, or any other field, from the Data object, use the following:

data.Data[0].email

WORKING EXAMPLE

Fizzix
  • 23,679
  • 38
  • 110
  • 176
2

For sometime now you can use:

xhr.responseJSON

without any parsing needed. hope it helps

Igneel64
  • 618
  • 4
  • 10
0

should parse the response to json object first,then get the data field from the response

var responseText = JSON.parse(xhr.responseText),
     data = responseText.Data;
Satpal
  • 132,252
  • 13
  • 159
  • 168
Raghava
  • 22
  • 2
0

When you make your ajax request you can provide dataType option:

dataType: 'json'

For such request when you receive response:

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

you can access your data like:

var data =  xhr.responseJSON

Full example:

  $ajax.({
    dataType: 'json',
    success: function( xhr ) {
      var yourData =  xhr.responseJSON;
      console.log( yourData );
    },
  });
Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
0
var jsonResponse = JSON.parse(xhr.responseText);
console.log(jsonResponse);
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 3
    Please [edit] your code-only answer to add information. Please do so to add explanation, that would help fighting the misconception that StackOverflow is a free code writing service. – Yunnosch Aug 28 '19 at 06:18