php 未捕获的语法错误:JSON输入意外结束:将sql表行传递给JavaScript文件,但无法发现错误

igsr9ssn  于 12个月前  发布在  PHP
关注(0)|答案(1)|浏览(100)

我将sql表行传递给一个JavaScript文件,以便在网站页面加载后显示:
php代码:

$sql = "SELECT * FROM `publication_information`";
    $pubs = $conn->query($sql);
    
    while ($row = mysqli_fetch_assoc($pubs)) {
      $existing_publications[] = $row;
    }  
        $willies = json_encode($existing_publications);
        echo $willies;

JavaScript代码:

function WORK(){
    var xhr = new XMLHttpRequest();
    var url = "/shoba/publications.php";
    
    
     xhr.onreadystatechange = function() {
      // Check if the request is completed and successful
      if (xhr.readyState == 4 && xhr.status == 200) {
        // Parse the JSON response
        var data = JSON.parse(xhr.responseText);
 
        // Do something with the data
        console.log(data+" success");
      } else {
          console.log(error);
      }
    };
    xhr.open("GET", url, true);
    xhr.send();
    alert("reached function end");
}

在调用函数时,到达了alert,但我得到了uncaught错误:

VM65:1  Uncaught SyntaxError: Unexpected end of JSON input

但我不能发现什么是错误的,据我所知,因为我使用了一个自动功能,它应该工作,但可悲的是它没有。你能告诉我怎么了吗?

xdnvmnnf

xdnvmnnf1#

除非保证格式正确,否则建议在解析JSON字符串时使用try..catch块。
下面的示例给出了问题所在以及导致解析器失败的内容。

var responseText = xhr.responseText;

try {
  var data = JSON.parse(responseText);
  console.log(data);
} catch (ex) {
  console.warn(ex.message);
  console.info('"' + responseText + '"');
}

我不知道PHP端有什么问题,但是here,我们看到json_encode可能返回null。如果$pubs没有项目或者null没有项目,你有没有检查过返回什么JSON字符串?

相关问题