简体   繁体   English

SyntaxError: Unexpected token < in JSON at position 0 ajax ZE1BFD762321E409CEE4840

[英]SyntaxError: Unexpected token < in JSON at position 0 ajax php

I'm building a website using PHP & Ajax.我正在使用 PHP 和 Ajax 构建网站。 I can't fetch data.我无法获取数据。 I constantly get "SyntaxError: Unexpected token < in JSON at position 0 " However, the data is sent to my database successfully and there're no errors in the network.我经常收到“SyntaxError: Unexpected token < in JSON at position 0” 但是,数据已成功发送到我的数据库,并且网络中没有错误。

Ajax file: 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);
    });
});

PHP file with json_encode带有 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);
};  
?>

It seems like server doesn't respond with JSON but with HTML (maybe it responds with HTML page describing the error occurred).似乎服务器没有响应 JSON 但 HTML (也许它响应 HTML 页面描述发生的错误)。 Check what the backend response is exactly.检查后端响应到底是什么。

for friends who want to check up-to-date, if there is any HTML code information on the page where you are processing the code, it reads the information sent from ajax but returns an error.想查看最新的朋友,如果你正在处理代码的页面上有任何HTML代码信息,它会读取从ajax发送的信息但返回错误。 Therefore, there should not be any HTML code on the processed page.因此,处理后的页面上不应有任何 HTML 代码。 Otherwise you will get an error.否则你会得到一个错误。 Note that the page is purely php codes.请注意,该页面纯粹是 php 代码。 This way my problem was fixed.这样我的问题就解决了。 It is very simple and requires attention.它非常简单,需要注意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM