2014-07-03 10 views
14

Mam XMLHttpRequest() funkcja podane poniżejJak uzyskać pole "Dane" z xhr.responseText?

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

gdzie xhr.responseText wartość powraca jako

{ 
    "$id": "1", 
    "ContentEncoding": null, 
    "ContentType": null, 
    "Data": [ 
     { 
      "$id": "2", 
      "email": "[email protected]" 
     }, 
     { 
      "$id": "3", 
      "email": "[email protected]" 
     } 
    ], 
    "JsonRequestBehavior": 1, 
    "MaxJsonLength": null, 
    "RecursionLimit": null 
} 

Jak mogę uzyskać pole z responseTextData?

Odpowiedz

24

użycie JSON.parse(), jak:

var data=xhr.responseText; 
var jsonResponse = JSON.parse(data); 
console.log(jsonResponse["Data"]); 
8

Najpierw należy przeanalizować responseText w JSON, do tego należy użyć JSON.parse(). Następnie możesz uzyskać do niego dostęp za pomocą klawisza.

var json = JSON.parse(xhr.responseText); 
var yourData = json.Data; // or json["Data"] 
1

po prostu otrzymać e-maila, lub jakiejkolwiek innej dziedzinie, z obiektu Data, użyć następujących:

data.Data[0].email 

WORKING EXAMPLE

0

powinien najpierw przeanalizować odpowiedź na obiekt Json, a następnie ge t pole danych z odpowiedzi

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

na jakiś czas teraz można użyć:

xhr.responseJSON 

bez parsowania potrzebne. mam nadzieję, że pomoże

Powiązane problemy