0

我第一次尝试使用 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;
4

1 回答 1

1

您需要将它们作为 json 字符串回显:

http://us3.php.net/manual/en/function.json-encode.php

然后ajax成功处理程序/回调需要将该字符串解码为js对象......

如何解码 JSON 字符串?

讨论如何解码 JSON。奇怪且有些遗憾的是,Javascript Object Notation 似乎在它所命名的语言中没有一个好的本地解码器。(如果有请指正!)

于 2013-01-28T21:26:38.223 回答