简体   繁体   中英

How to get some field from json object through xhr response

my json object look like this {"status":"4", "detail_user":{ "userId" : "1", "fullName" : Diga } }

and my XmlHttpRequest

var email    = $$(page.container).find('input[name="email"]').val();
var password = $$(page.container).find('input[name="password"]').val();
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){ 
  //var response = JSON.parse(xhr.responseText);
  //alert(response.status);
  //alert(response.detail_user);
  var data=xhr.response;
  var data2=xhr.responseText; // respon like json object above
  alert(data);
  alert(data2);
  alert(data2.detail_user);
  alert(getJSON(data2.status)); //respon undefined
  var asd = JSON.stringify(data2).replace(/\"/g,"");
  alert(asd);
  console.log(xhr.response);//this is the response from the server
  }
}
params = "email=" + email + "&password=" + password;
xhr.open("POST", server+"sign-in/auth",true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(params);

my coding in cordova and phonegap, actually for show all object of json success but when i show only some field i get respon undefined.

Your data2 was a string, hence doesn't have property status . Change:

alert(getJSON(data2.status));

to

alert(getJSON(data2).status);

I assumed function getJSON() is returning JS object.

JSON.parse(data, (key, value) => {

console.log(key); // log the current property name, the last is "". return value; // return the unchanged property value. });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM