[英]Get json array from php to javascript with $.getJSON()
我有application.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
您可以在脚本中使用var temp并将数据存储在该变量中。
var x;
<script type="text/javascript">
x='<?php echo $comparisonResult; ?>';
</script>
听起来像sessionStorage或cookie的用例。
我认为最好的方法是在第一个发布请求的响应中返回所需的服务器数据,如下所示:
$.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
由于某种原因(错误的url,无效的json等),您的$ .getJSON失败。
试试这个进行调试:
$.getJSON("/data.php", function (serverData) {
console.log(serverData);
}).fail(function(j, t, e) {
console.error(e);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.