我有一个有倒计时的网站。一旦时间为0,我将使用来自JS的AJAX请求,然后使用PHP更新一个新的倒计时和竞赛。在新的AJAX请求中,我需要返回两个值:图像url和count_down时间。
$.ajax({url: "new_contest.php", success: function(result) {
$("#count_down).time(result);
});
我可以用成功函数返回结果,但是我只能返回其中的一个结果。我还尝试从AJAX页面创建一个session
,然后在JS变量中放置一个会话。但是这个过程非常复杂,我觉得有更简单的方法来完成这个任务.
我认为不需要显示new_contest.php
的代码(AJAX页面),该页面上的所有代码都用于输出这两个所需的值:)
发布于 2017-03-25 19:38:35
in php
<?php
error_reporting(0);
$var = array('time' => "2017-12-23 23:23:23",'someval' => 'hello');
print_r(json_encode($var));
在ajax
$.post('1.php',{val: 'val'}).done(function(data){
if(data!='null' && typeof data !=='undefined'){
data = JSON.parse(data);
$("#count_down").time(data.time);
$("#count_up").time(data.someval);
}
})
发布于 2017-03-25 19:33:13
如果要从php文件中提取多个值,则应该使用json .
在你的html文件中。
<script>
var xmlhttp = new XMLHttpRequest();
var url = "yourphpfile.php";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var thisvariable = JSON.parse(this.responseText);
yourfunction(thisvariable); //do somthing here for the returned json object
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
然后在php文件中
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
希望这能有所帮助。
发布于 2017-03-25 19:33:31
如果将PHP函数的结果放入数组中,则可以使用json_encode($yourArray)将其作为JSON返回到前端。
在AJAX成功调用中可以像PHP数组一样访问JSON。https://www.tutorialspoint.com/json/
https://stackoverflow.com/questions/43020984
复制相似问题