javascript - 使用 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() 方法?
解决方案
您需要一种方法让 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);
}
您应该能够修改这些示例以满足您的需要。
推荐阅读
- c - c 的 void* 作为参数和返回值
- sql - Oracle:根据变量和历史表获取价格
- c++ - 如何使用cmd链接不同目录的目标文件?
- java - Hibernate - JPA - OneToMany 和 CascadeType.ALL
- android-studio - 如何在android中将一个类的方法调用到另一个类
- python - 列出安装在 sklearn 中的子包和功能
- javascript - Unshift 在函数 Javascript 中不起作用
- python - Spacy:尝试设置冲突的 doc.ents:令牌只能是一个实体的一部分,因此请确保您设置的实体不重叠
- python - 查找 list.py 中的最大数
- numpy - 我想用 randomforest predict_proba 的结果制作一个新的数据框