dongzongzhi6953 2015-10-08 17:12
浏览 494
已采纳

'SyntaxError:意外的输入结束'。 解析JSON时出错?

I've got this AJAX function:

function fetchSocialCount(type,fileSrc){
    var count = null;
    var req = new XMLHttpRequest();
    req.onload = function(){
        if(req.status === 200 && req.readyState === 4){
            console.log(req.responseText);
            count = JSON.parse(req.responseText);
        }
    }
    req.open("GET","../scripts/php/returnSocialCount.php?type=" + type + "&fileSrc=" + fileSrc,false);
    req.send();
    if(count !== null){
        return count;
    }
    else{
        console.log("The AJAX request has failed.");
    }
}

But when I run it, I get a 'SyntaxError: Unexpected end of input'. error. The Chrome Dev Tools also covers the count = JSON.parse(req.responseText); part in blue, so I'm guessing it's something wrong with the JSON I'm recieving. From the PHP script, I'm sending a pretty complex JSON object, so I tried to send a really basic one and it worked without problems.

This is the part of the PHP script that sends the response:

echo '{"likes":'.$json->videoListArray[$i]->likes . ',"dislikes":' . $json->videoListArray[$i]->dislikes . '}';

Is there something wrong with the syntax of the echo? What's the problem?

Thanks.

  • 写回答

2条回答 默认 最新

  • drnf09037160 2015-10-08 17:20
    关注

    It appears that there is probably a syntax error in your JSON that you're returning. It's not usually a good idea to manually create JSON for this very reason. Try creating an associative array and then use json_encode() to return the desired data to the ajax call:

    // Create the array
    $data = array();
    
    // Add the data
    $data['likes'] = $json->videoListArray[$i]->likes;
    $data['dislikes'] = $json->videoListArray[$i]->dislikes;
    
    // Generate JSON from the array and return the desired results
    echo json_encode($data);
    

    Reference Documentation:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大