简体   繁体   English

JSON输入意外结束

[英]Unexpected end of JSON input

I'm having a little trouble figuring out how to fix this error I'm getting. 我在弄清楚如何解决此错误时遇到了一些麻烦。 My code is as follows. 我的代码如下。

It all starts with a AJAX request whenever the user moves their mouse on the webpage. 每当用户在网页上移动鼠标时,所有操作都以AJAX请求开始。

$('body').mouseover(function() {
    $.ajax({ 
        url: '/core/home.php',
        data: {action: 'refresh'},
        type: 'post',

Next, the PHP file (home.php) executes a couple methods to get all the needed data and sends it back to AJAX Request. 接下来,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;
}

Once the AJAX Request receives a success, the following executes 一旦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');
        }
    });
});

Unfortunately this code results into an error: Unexpected end of JSON input . 不幸的是,此代码导致错误: Unexpected end of JSON input Any help is much appreciated. 任何帮助深表感谢。

Rather than returning variable you need to echo it 而不是返回变量,您需要回显它

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM