How to get “Data” field from xhr.responseText?

后端 未结 7 1028
别跟我提以往
别跟我提以往 2020-12-09 14:40

I have XMLHttpRequest() function given below

var searchFriendRequests = function (userid) {
    var xhr = new XMLHttpRequest();
    xhr.open(\'G         


        
相关标签:
7条回答
  • 2020-12-09 15:12

    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 );
        },
      });
    
    0 讨论(0)
  • 2020-12-09 15:24

    use JSON.parse(), like:

    var data=xhr.responseText;
    var jsonResponse = JSON.parse(data);
    console.log(jsonResponse["Data"]);
    
    0 讨论(0)
  • 2020-12-09 15:25

    For sometime now you can use:

    xhr.responseJSON
    

    without any parsing needed. hope it helps

    0 讨论(0)
  • 2020-12-09 15:26

    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;
    
    0 讨论(0)
  • 2020-12-09 15:27

    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"]
    
    0 讨论(0)
  • 2020-12-09 15:32

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

    data.Data[0].email
    

    WORKING EXAMPLE

    0 讨论(0)
提交回复
热议问题