weixin_33709219 2016-06-11 10:59 采纳率: 0%
浏览 498

JSON输入意外结束

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.

$('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.

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

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. Any help is much appreciated.

  • 写回答

1条回答 默认 最新

  • weixin_33696822 2016-06-11 11:19
    关注

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

报告相同问题?