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

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料