简体   繁体   中英

Read 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 output is

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

How to fix that thanks

If you are using normal javascript, You want to loop through the properties of an object, which u can do it in javascript with 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>

From the MDN documentation about JSON.parse :

The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value.

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

Here is a simpler example:

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

You usually only use a reviver function if you want to transform the parsed data immediately. You can just do:

var obj = JSON.parse(json);

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

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