【问题标题】:Passing JSON with xmlhttpRequest request in JS在 JS 中使用 xmlhttpRequest 请求传递 JSON
【发布时间】:2012-01-03 08:40:13
【问题描述】:

我将 JSON 从 php 服务器回显到浏览器。我非常精通 XML,但对 JSON 很陌生。有人可以告诉我如何正确地从 xmlhttpRequest 中提取 JSON,然后将其传递到数据中,也就是警报。

我的 JSON(来自 PHP 服务器)

       {"data": {
       "message": "Open the Pod bay doors, Hal",
       "type": "request",           
       "replies" => array(
                 "id": "12321"
                 "message": "I'm sorry Dave, I'm afraid I can't do that!"
        )
        }
        }

我在 JS 中的请求返回 JSON,但是我无法捕获它或提取内部信息...我的 ajax 函数是...

function ajax(site){  
    xmlhttp.open("GET","site",true);
    xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4) {
       if (xmlhttp.status!=404) {
       var resp =new Function("return "+xmlhttp.responseText)();

     }
   }
 xmlhttp.send(null);
 }

然后我调用window.onload中的函数

    window.onload = runJSON()

function runJSON(){
    var site = "http://localhost/sites/sandbox/json.php"
    ajax(site);
    ... this is what i am unsure about... how do I access the data in the object
}
alert(data);
}

【问题讨论】:

    标签: php javascript ajax json parameter-passing


    【解决方案1】:
    "replies" => array(
                 "id": "12321"
                 "message": "I'm sorry Dave, I'm afraid I can't do that!"
        )
    

    需要

    "replies": {
      "id": "12321",
      "message": "I'm sorry Dave, I'm afraid I can't do that!"
    }
    

    在 JavaScript 中,您可以通过运行 JSON.parse(str) 将 JSON 转换为 JS 对象,您应该从 onreadystatechange 处理程序内部的回调中获取您的 str

    if (xmlhttp.status!=404) {
      var resp =new Function("return "+xmlhttp.responseText)();
      ajaxDone(resp);
    }
    function ajaxDone(str) {
      try {
        var data = JSON.parse(str);
        console.log(data);
      } catch (x) {
        // TODO: see what happened
      }
    }
    

    注意:JSON.parse 在旧版浏览器中不存在。如果你也想支持它们,你将需要一个可以填充它们的库,比如 jQuery(顺便说一下,这也会消除 AJAX 部门的很多痛苦)。

    【讨论】:

      【解决方案2】:

      首先你应该解析 JSON 数据并从 ajax 函数返回。

      var resp =new Function("return "+xmlhttp.responseText)();
      

      用, 改变这一行

      return JSON.parse( xmlhttp.responseText );
      

      然后在 runJSON 函数中,将该 json 对象放入一个变量中。

      var jd = ajax(site);
      

      然后就可以访问json中的所有数据了。

      例如。 alert( jd.data.message ); 在屏幕上显示“打开 Pod 舱门,哈尔”作为消息。

      【讨论】:

        猜你喜欢
        • 2013-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-01
        • 2014-08-16
        • 1970-01-01
        相关资源
        最近更新 更多