首页 > 解决方案 > 使用 JavaScript Fetch() 时显示 PHP 验证错误

问题描述

我想在前端使用 JavaScript fetchAPI 时输出一条在 PHP 后端工作的错误消息。这里有一个非常相似的问题:Output PHP Form Validation Error Messages When Using JavaScript Fetch API,但我认为由于该问题中的代码量,问题看起来比实际情况更令人生畏。从表面上看,这个人正在做我正在做的同样的教程。

在我的情况下(在使用 JS 之前fetch()),如果 PHP 验证中出现错误,则会使用以下代码将错误消息回显到屏幕上:

<?php 
    if(isset($error)) {
        foreach($error as $errorMessage) {
            echo "<p>You have an error: {$errorMessage}</p>";
        }
    }
?>

表单处理的简化版本是:

<?php

    // note $postTitle is a variable given to the title of a post submitted via an HTML form

    if(!preg_match('/^[a-zA-Z0-9\s]+$/', $postTitle)) {
        $error[] = "Post Title can be letters and numbers only";
    }

    // if no errors process submission
    if (!isset($error)) {

        try {

        // PDO prepared statements that update the database with article/post information
    
        } catch (PDOException $e) {
            echo "There is an error: " . $e->getMessage();
        }

    }

?>

Javascript是:

var forms = document.querySelectorAll('form'),

forms.forEach(item => {

        item.addEventListener("submit", function(e) {

            e.preventDefault();

            const formData = new FormData(this);

            fetch("news-posts.php", {
                method: 'post',
                body: formData
            }).then(function(response){
                return response.text();
            }).then(function(data){
                console.log(data);
            }).catch(function (error){
                console.error(error);
            })

            item.remove();

    })

})

问题是虽然错误处理在后端仍然按预期工作,但是如何在前端输出错误消息,现在它使用 JS Fetch() 方法?

标签: javascriptphperror-handlingpromisefetch

解决方案


您需要一种方法让 JS 知道它何时收到错误。理想情况下,您的后端会返回与错误相关的 http 状态代码,您可以在前端检查这一点。

后端:

if (isset($error)) {
    header('400 Bad Request');
    // output errors here
}

前端:

fetch("news-posts.php", {
  method: 'post',
  body: formData
}).then(function(response) {
  if (!response.ok) {
    // handle errors here
  }
});

此外,您可能希望以 json 格式输出错误并在 JS 中循环遍历它们。您不需要<p>为每个错误输出标签,只需输出数据即可。这些标签可以由 JS 本身动态添加。

下面的示例循环遍历一个data对象,为每个项目创建一个<p>元素并将它们附加到具有 id 的 div 中error

let errorElement = document.querySelector('#error');
for (let error of data.errors) {
  let listItem = document.createElement('p');
  listItem.textContent = error.message;
  errorElement.appendChild(listItem);
}

您应该能够修改这些示例以满足您的需要。


推荐阅读