3

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

Cezar
  • 55,636
  • 19
  • 86
  • 87
DeLe
  • 2,442
  • 19
  • 88
  • 133

2 Answers2

2

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>
raduns
  • 765
  • 7
  • 18
1

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.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143