javascript - JSON 输入意外结束

标签 javascript php jquery json ajax

我在弄清楚如何解决我遇到的这个错误时遇到了一些麻烦。我的代码如下。

每当用户在网页上移动鼠标时,这一切都从 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/

相关文章:

javascript - 检查元素是否包含加载和更改时的特定文本

javascript - Grails如何让AJAX发送从模板表单中编辑的对象

javascript - 在 React 中使用任何形式的 Map 函数都会导致未定义的错误

php - 禁用目录的 .htaccess

javascript - 在html中 float 多个元素

javascript - 追踪 knockout 事件

php - 使用 mysql/PHP 进行本地化

php - 如何防止在多次重新加载/刷新页面时超过 max_user_connections?

javascript - replaceWith() 在 .hover() 中不起作用

javascript - 嵌套的 $(document).ready() 和 $(window).load() 事件之间的区别