php - 为什么我的 echo json_encode($data) 实际上会在我的页面上显示某些内容以及如何避免这种情况(ajax/php 表单验证)
问题描述
编辑:我解决了我的问题,因为我有一个被遗忘的“要求”运算符在代码中搞砸了。很抱歉没有早点意识到这一点,感谢您的宝贵时间。
我对网络开发有点陌生,这是我第二次在网站上使用 AJAX。
这只是使用 ajax 和 php 客户端验证的联系表单验证。问题是:我的代码实际上在验证部分按预期工作,因为一切正常,但我不明白我遗漏了什么或做错了什么,因为我的网站顶部有一行(在每个页面上,不是只有联系页面顺便说一句)我显然不想要
我知道它来自我的 php 代码,实际上与我的 json_encode($data) 相呼应,但我不明白为什么以及如何避免这种情况
这是我的代码:
JS:
let resultMessage = $('#resultMessage')
let form = $('#contact_form')
form.submit(function(e){
$('span.error').empty()
e.preventDefault()
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: 'json',
success: function(response) {
if(response.success == true){
resultMessage.html('Message sent succesfully')
} else {
resultMessage.html('Fail')
if (response.errors.nom != null) {
$('#name_error').html(response.errors.nom);
}
if (response.errors.email != null) {
$('#email_error').html(response.errors.email);
}
if (response.errors.message != null) {
$('#message_error').html(response.errors.message);
}
}
},
error: function(){
console.log('error')
}
})
})
PHP
$success = false;
$errors = [];
// inputs validation
$errors = textInputValidation($errors, $name, 'name', 2, 50);
$errors = emailValidation($errors, $email, 'email');
$errors = textInputValidation($errors, $message, 'message', 10, 5000);
// if there is no error =>
if (count($errors) == 0) {
// code actualy sending the message
$success = true;
}
$data = array(
'errors' => $errors,
'success' => $success
);
header('Content-type:application/json');
echo json_encode($data);
所以这段代码可以工作,但问题是我把这条线放在我的网站上
{"errors":{"name":"please fill this field","email":"please fill this field","message":"please fill this field"},"success":false}
它在每个页面上,不仅在联系页面上,而且当验证正常并且表单或任何地方没有错误时,它甚至都不会改变。
我可能遗漏了一些非常基本的东西,对此感到抱歉。
谢谢你的帮助
解决方案
推荐阅读
- json - 无法读取未定义的属性“rotationOffset”
- yaml - 如何将 YAML 锚合并为列表项并覆盖值
- google-apps-script - GAS:通过自定义 UI 菜单的脚本授权失败,并显示“您无权执行该操作”。
- ruby-on-rails - 我的 js 文件中有两个 ajax 获取请求。我无法阻止第二个请求中的默认行为
- react-native - realm react-native:如何正确查询字符串数组
- reporting-services - 如何为空的 SSRS 组显示一些静态文本?
- java - 如何安装 jtransc?
- javascript - 是否可以自动选择带有 chrome 扩展名的文件输入的文件?
- jquery - div元素上的悬停事件
- php - 稍后初始化(子)类并将其附加到实例化的父级