gpt4 book ai didi

javascript - 从 php 服务器读取 json

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:44 25 4
gpt4 key购买 nike

我想使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com