Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get "Data" field from xhr.responseText?

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": "[email protected]"         },         {             "$id": "3",             "email": "[email protected]"         }     ],     "JsonRequestBehavior": 1,     "MaxJsonLength": null,     "RecursionLimit": null } 

How can I get the Data field from the responseText?

like image 1000
Midhuna Avatar asked Jul 03 '14 06:07

Midhuna


People also ask

What is XHR responseText?

responseText. The read-only XMLHttpRequest property responseText returns the text received from a server following a request being sent.

Is it possible to convert XHR response text to an object?

However, you’d get an error. Because the xhr.responseText is a string, you can easily manipulate it. To work with the data, you need to convert it back into an object. You can do this using the JSON.parse () method.

How to get the response from a web server using XMLHttpRequest?

To receive the response from a web server, you can use the responseText or responseXML property of the XMLHttpRequest object. In this article, we are going to look at the responseText in more detail.

How to parse JSON response in Ajax?

var responseText = JSON.parse (xhr.responseText), data = responseText.Data; When you make your ajax request you can provide dataType option: If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler.

What is XMLHttpRequest object used for?

The XMLHttpRequest object is used to send and receive data between a web browser and web server. In this article, we are going to look at how to receive data from a web server.


1 Answers

use JSON.parse(), like:

var data=xhr.responseText; var jsonResponse = JSON.parse(data); console.log(jsonResponse["Data"]); 
like image 62
Sudhir Bastakoti Avatar answered Oct 06 '22 01:10

Sudhir Bastakoti