JavaScript Fetch API在使用JSON时无法按预期返回then()方法中的数据(在后端使用PHP)

vcirk6k6  于 2022-10-30  发布在  Java
关注(0)|答案(1)|浏览(1108)

我有一个简单的表单,允许更新讨论板标题(HTML组件是一个给定主题沿着图片板)。2我目前正在设置它,MySQL数据库在后端通过PHP进行更新,前端使用JavaScriptx 1 m0n1xAPI将新值从数据库拉回到页面上。当在表单上单击“更新”按钮时,所有这些操作都会发生。

问题

当点击表单上的“更新”按钮时,PHP / MySQL更新发生,数据库被正确更新,JavaScript fetch()返回一个响应对象,该对象返回status: 200statusText: OK属性。然而,当它点击承诺的第一个.then()方法时,它会抛出一个错误。
我得到的错误是:

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

这显然是指页面顶部的HTML开头行。
我有点不知道是什么导致了这个问题?

JavaScript语言

let form = document.querySelector('form');

if (form) {
    form.addEventListener('submit', function(e) {
        if (e.submitter && e.submitter.classList.contains('js-edit-button')) {
            e.preventDefault();

            var formData = new FormData(this);

            formData.set(e.submitter.name, e.submitter.value);
            formData.set('json_resp', 'yes'); // reference to be used in the PHP

            fetch(
                theURL, {
                method: 'post',
                body: formData
            })
            .then((response) => {
                if (response.status === 200) {
                    response.json().then((json) => {

                        // board_name column from database
                        let newBoardName = json.board_name;

                        let boardTitleHTML = document.querySelector('.board-heading');

                        boardTitleHTML.textContent = newBoardName;

                    });

                    console.log(response);   
                }

            }).catch((error) => {
                console.error(error);
            })
        }
    }) // submit event listener
} // if (form)

PHP语言

// UPDATE BOARD NAME
// initially update the MySQL database

if(isset($_POST['submit-new-board-name'])) {

    $newBoardName = htmlspecialchars($_POST['edit-board-name']);
    $boardId = htmlspecialchars($_POST['board-id']);

    // form validations that check for errors have been omitted from this code

    if(!isset($error)) {

        $sql = "UPDATE boards SET
        board_name = :board_name
        WHERE board_id = :board_id AND user_id = :user_id
        ";

        $stmt = $connection->prepare($sql);

        $stmt->execute([
            ':board_name' => $newBoardName,
            ':board_id' => $boardId,
            ':user_id'=> $sessionId
        ]);

        // FETCH AS JSON TO UPDATE BOARD TITLE

        if(isset($_POST['json_resp'])) // this 'json_resp' name is set in the javascript FormData code
        {
            $board_stmt = $connection->prepare("SELECT * FROM boards
            WHERE board_id = :board_id AND user_id = :user_id");

            $board_stmt -> execute([
                ':board_id' => $boardId,
                ':user_id' => $sessionId // generated from user login
            ]);

            // this fetches the board_id, board_name(this is the board title) and user_id columns from the database
            $board_row = $board_stmt->fetch();

            header('Content-type: application/json');
            echo json_encode($board_row);
            exit;
        }

    }
}

HTML格式

<-- this h1 value is stored in the form in the $dbBoardName variable so it can be edited -->
<h1 class="board-heading">Heading To Be Changed</h1>

<form method="post">
    <input type="hidden" name="board-id" value='<?= $dbBoardId ?>'>
    <div class="form-row">
        <label for="board-name">BOARD NAME:</label>
        <input id="board-name" name="edit-board-name" value='<?= $dbBoardname ?>' type="text">
    </div>
    <button type="submit" name="submit-new-board-name" class="js-edit-button">Update</button>
</form>
yjghlzjz

yjghlzjz1#

看起来你的PHP脚本没有返回JSON,而是返回了一个呈现的HTML文档。你注意到的错误Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON可能不是在引用你的主页,而是在解析服务器的响应为JSON时失败。我建议调试PHP,或者至少检查开发工具中的网络选项卡,以确认你要获取的响应是你所期望的。

相关问题