【问题标题】:SyntaxError: Unexpected token < in JSON at position 0 ajax phpSyntaxError:意外的令牌 < 在 JSON 中的位置 0 ajax php
【发布时间】:2020-05-03 10:36:36
【问题描述】:

我正在使用 PHP 和 Ajax 构建网站。 我无法获取数据。 我经常收到“SyntaxError: Unexpected token

Ajax 文件:

document.getElementById("btnSendPrivateMessage").addEventListener("click", function (e) {
    e.preventDefault();

    let chatId = this.dataset.chatid;
    let text = document.querySelector('#privateMessageText').value;

    console.log(chatId);
    console.log(text);


    //sent to DB
    let formData = new FormData();

    formData.append("text_message", text);
    formData.append("chat_id", chatId);

    fetch("ajax/saveMessage.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(result => {
        console.log("Success:", result);
    })
    .catch(error => {
        console.error("Error:", error);
    });
});

带有 json_encode 的 PHP 文件

<?php 
require("../classes/Db.class.php");
require("../classes/ChatPrivateMessage.class.php");
require("../datetime.php");
session_start();  

if(!empty($_POST)){
    header("Content-type: application/json");

    $m = new ChatPrivateMessage();

    $m->setChatId($_POST['chat_id']);
    $m->setText($_POST['text_message']);
    $m->setUser1($_SESSION['user_id']);
    $m->setDate(getTime());

    $textM = htmlspecialchars($m->getText()) ;


    $m->saveMessage();

    $response = [
        "status" => "success",
        "body" => $textM,
        "message" => "something"
    ];

    header("Content-type:application/json"); 

    echo json_encode($response);
};  
?>

【问题讨论】:

  • 响应正文是什么?
  • 您可能会收到一些缓冲的 html,因为报告了某种 php 错误。观察正文(根据@kevmo314 的建议),您将了解根本问题。
  • @kevmo314 responde budy 不是问题,即使我把它串起来我仍然得到同样的错误

标签: javascript php json ajax


【解决方案1】:

似乎服务器没有用 JSON 响应,而是用 HTML 响应(也许它用描述发生错误的 HTML 页面响应)。检查后端响应到底是什么。

【讨论】:

  • 以及如何查看后台响应?
  • 在调用可能崩溃的 response.json() 函数之前尝试 console.log 'response'。
  • 它返回 response.text(),然后 Success 未定义,但 response.json() 有问题。我不知道如何解决它,Google 的任何技巧都不起作用。
猜你喜欢
  • 2020-02-05
  • 2021-09-12
相关资源
最近更新 更多