我第一次尝试使用 json 验证表单。除了我今天阅读的内容外,我不确定所有细节。不幸的是,我正在尝试做什么的例子并不多。就是这样,我需要检查多个输入字段以检查它们是否在 mysql 数据库中。所以我需要将它们发送到 php 页面,该页面会检查它们,如果它找到一个不在数据库中的 foreach 循环中断,并且该变量值可以用于类似$value." is not a registered email";
. 我不完全知道如何将值返回到我的 html 表单页面。所以我会告诉你我有什么。可能有一百万个错误。您提供的任何帮助将不胜感激。
在表单页面上:
<script>
$(function(){
$("#send").click(function(e){
e.preventDefault();
$.post("ajax2.php", $("#myForm").serialize(),
function(data){
if(data.check == '2'){
alert(data.message);
}
}, "json");
});
});
</script>
<html>
<form name="myForm" action="ajax.html" method="post" enctype="multipart/form-data">
<input id="file" name="uploaded[]" type="file" multiple /><br>
title: <input name="title" id ="title"><br>
box1: <input type="text" id = "a" name="a"><br>
box2: <input type="text" id = "b" name="b"><br>
box3: <input type="text" id = "c" name="c">
<input type="submit" name="send" id="send" value="send" ">
</form>
</html>
在 ajax2.php 上:
<?php
$db = new mysqli('localhost', 'root', 'oreo', 'test');
foreach($_POST as $key=> $for) {
if(!empty($for) && $key != 'send' && $key != 'title') {
$usercheck = "SELECT email FROM users WHERE email = '$for'";
$usercheck = $db->query($usercheck);
if($usercheck->num_rows > 0) {$check="1"; continue;}
if($usercheck->num_rows == 0){$check="2"; break;}
}
}
if($check == "2") {
$message = $for." is not a regestered email";
echo json_encode($message);
}
$return_arr["check"] = $check;
$return_arr["message"] = $message;
echo $return_json;