我想使用 javascript(不是 jquery)从 php 服务器读取 json
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
json = xmlhttp.responseText;
JSON.parse(json, function (key, val) {
alert(key + '-'+ val);
});
}
}
在 php 文件中我这样做
$data = array();
$data['id'] = '1';
$data['name'] = '2';
print json_encode($data);
但是输出是
id-1
name-2
-[object Object] // why??
如何解决这个问题
最佳答案
如果您使用普通的 javascript,您想要循环访问对象的属性,您可以在 javascript 中使用 for in
语句来完成此操作。
<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>
关于javascript - 从php服务器读取json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18161636/