我在弄清楚如何解决我遇到的这个错误时遇到了一些麻烦。我的代码如下。
每当用户在网页上移动鼠标时,这一切都从 AJAX 请求开始。
$('body').mouseover(function() {
$.ajax({
url: '/core/home.php',
data: {action: 'refresh'},
type: 'post',
接下来,PHP 文件 (home.php) 执行几个方法来获取所有需要的数据并将其发送回 AJAX 请求。
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
json_encode($arr);
return $arr;
}
一旦 AJAX 请求成功,就会执行以下内容
success: function(output) {
obj = JSON.parse(output);
// Separate the parts of the JSON string
vacs = obj[0];
users = obj[1];
// Show the result at the correct position on the webpage
$('#vac_num').html(vacs);
if(vacs == 1) $('#vac_txt').html('is'); else $('#vac_txt').html('zijn');
$('#users_num').html(users);
if(users == 1) $('#users_txt').html('is'); else $('#users_txt').html('zijn');
}
});
});
不幸的是,此代码会导致错误:JSON 输入意外结束
。
非常感谢任何帮助。
最佳答案
您需要回显它,而不是返回变量
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
echo json_encode($arr);
}
关于javascript - JSON 输入意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37762940/