dongseshu0698 2015-02-19 23:43
浏览 119
已采纳

JSON无法接受json_encode()数组

I am sending a simple array from my PHP file,

//example.php
if(0){
    return json_encode(['status'=>false, 'message'=>'Please enter a username']);
}

and in my ajax.js I have everything working, including the XHR object, and event handlers. All is find, except this line.

 // ...
 var x = JSON.parse(xmlhttp.responseText);
 console.log(x); 
// ...

But, I am getting the following error.

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

I don't understand this. All the code is correct. Before using JSON, I used to pass from values from PHP using echo 'ok' and just do if(xmlhttp.responseText) == 'ok and it worked fine, but not with json

  • 写回答

1条回答 默认 最新

  • dongnigeng1295 2015-02-20 00:18
    关注

    Two problems:

    • you use return which does not print anything to the output wheras echo actually prints text. Try using:

    • if(0) will always fail, so you will never print anything. You should use if(1) as trivial test. It is possible that you're PHP code can fail, but in that case you better also return an JSON formatted error message.

    Something like:

    if(test) { //test means you can do the action
        //do action
        echo json_encode(['return' => 'ok','result' => 'foobar']);
    } else {
        echo json_encode(['return' => 'error']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)