Reading json from php server

I want to read json from php server using javascript (not jquery) like

xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { json = xmlhttp.responseText; JSON.parse(json, function (key, val) { alert(key + '-'+ val); }); } } 

in php file i do

 $data = array(); $data['id'] = '1'; $data['name'] = '2'; print json_encode($data); 

But the conclusion

 id-1 name-2 -[object Object] // why?? 

How to fix it thanks

+4
source share
2 answers

If you use regular javascript, you want to view the properties of the object that you can do in javascript using the for in statement.

 <script> var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { alert(xmlhttp.responseText); var data = JSON.parse(xmlhttp.responseText); for(key in data) { alert(key + ' - '+ data[key]); //outputs key and value } } } xmlhttp.open("GET","sample.php",true); //Say my php file name is sample.php xmlhttp.send(); </script> 
+2
source

From the MDN documentation about JSON.parse :

The examiner is ultimately called with an empty string and the highest value to allow conversion of the highest value.

Parsing {"id":"1","name":"2"} will create a JavaScript object. Therefore, at the last call to the reviver key function, the empty string is val , and val is the generated object.
The default string representation for any object is [object Object] , so the output you get is not surprising.

Here is a simpler example:

 // object vv alert('Object string representation: ' + {}); 

Usually you use the reviver function if you want to immediately convert the analyzed data. You can simply:

 var obj = JSON.parse(json); 

and then iterate over the object or directly access its properties. See Access / process (nested) objects, arrays, or JSON for more information.

+1
source

Source: https://habr.com/ru/post/1496309/


All Articles