JSON无法接受JSON_encode()数组

JSON unable to accept json_encode() arrays

本文关键字:JSON 数组 encode      更新时间:2024-02-23

我正在从我的PHP文件发送一个简单的数组

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

在我的ajax.js中,我的一切都在工作,包括XHR对象和事件处理程序。除了这一行,所有的都找到了。

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

但是,我得到了以下错误。

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

我不明白。所有代码都是正确的。在使用JSON之前,我曾经使用echo 'ok'从PHP传递值,只执行if(xmlhttp.responseText) == 'ok,它运行良好,但使用JSON 时效果不佳

两个问题:

  • echo实际打印文本时,使用不向输出打印任何内容的return。尝试使用:

  • if(0)总是会失败,因此您将从不打印任何内容。您应该使用if(1)作为琐碎的测试。PHP代码可能会失败,但在这种情况下,最好也返回JSON格式的错误消息。

类似于:

if(test) { //test means you can do the action
    //do action
    echo json_encode(['return' => 'ok','result' => 'foobar']);
} else {
    echo json_encode(['return' => 'error']);
}