使用$ .getJSON()从json数组获取json数组

时间:2014-01-30 09:51:03

标签: javascript php jquery html ajax

我有app.php页面,其中json数组与php回应。在客户端上,我希望在提交表单时按钮单击时使用$ .getJSON()获取json数组(submitHandler)。问题是如果我在$ .getJSON()中运行alert()或console.log()没有任何反应(我只在控制台中看到GET执行)。

代码:

$.getJSON('../views/application.php', function(data) {
     alert('alert1');
     if(data) {
         document.write(data.resp);
         alert('alert2');
     }
     else {
         alert('error');
     }
 });

GET http://localhost/app/views/application.php

3 个答案:

答案 0 :(得分:1)

您可以在脚本中使用var temp并将数据存储在该变量中。         

 var x;

   <script type="text/javascript">
      x='<?php echo $comparisonResult; ?>';
   </script>

答案 1 :(得分:1)

答案 2 :(得分:0)

我认为最好的方法是在第一个帖子请求的响应中返回所需的服务器数据,如下所示:

  $.post( "/first.php", function( serverData ) {
     var param = serverData.something;
     ...
     $.post( "/second.php", param, function( data ) {
        ...
     });
  });

如果您在两个不同的页面中使用这两个请求,则可以将serverData存储在localStorage中。

澄清之后编辑:

如果您在单击按钮时需要在ajax发布之前获取数据,则可以这样做:

$("#second-button").click(function() {
   $.getJSON("/data.php", function (serverData) {
      var param = serverData.something;
      $.post("/second.php", param, function(data) {
         ...
      });
   }
});

修改2

由于某种原因(错误的网址,无效的json等),你的$ .getJSON失败。

试试这个进行调试:

$.getJSON("/data.php", function (serverData) {
   console.log(serverData);
}).fail(function(j, t, e) {
   console.error(e);
});
相关问题