javascript - Read json from php server -
i want read json 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 do
$data = array(); $data['id'] = '1'; $data['name'] = '2'; print json_encode($data);
but output is
id-1 name-2 -[object object] // why??
how fix thanks
if using normal javascript, want loop through properties of object, u can in javascript for in
statement.
<script> var xmlhttp; if (window.xmlhttprequest) {// code ie7+, firefox, chrome, opera, safari xmlhttp=new xmlhttprequest(); } else {// code 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 , value } } } xmlhttp.open("get","sample.php",true); //say php file name sample.php xmlhttp.send(); </script>
Comments
Post a Comment