我第一次尝试使用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;
答案 0 :(得分:1)
你需要将它们作为json字符串回显:
http://us3.php.net/manual/en/function.json-encode.php
然后ajax成功处理程序/回调需要将该字符串解码为js对象...
谈论如何解码JSON。奇怪而有些遗憾的是Javascript Object Notation似乎没有一个好的原生解码器,因为它被命名为该语言。 (如果有,请纠正我!)