javascript - 从php服务器读取json

标签 javascript json

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

相关文章:

javascript - Sencha Touch 中的嵌套面板/工具栏

javascript - 将值从 JSON 移动到 javascript 数组

jquery - 使用 jQuery 从无序列表中输出 JSON 对象

javascript - 将下拉选择滚动条置于所选元素的中心

javascript - 无法使用 jQuery 获取带有溢出图像的视口(viewport)大小

javascript - 动态显示/隐藏记录子集?

javascript - 通过key获取json数据

java - Spring Boot 将 JSON 和简单属性传递给相同的映射

sql - Presto 生成 JSON 结果

javascript - React.js 更新组件作为参数传递