0

我有一个表格,我想在其中进行验证。但是有一个字段我想验证编写查询。我不希望表单回发,因为在回发后,表单中填写的所有值都丢失了。有什么办法可以在没有回发的情况下编写查询,或者如果我必须回发如何保留这些值?请帮忙

4

3 回答 3

3

如果您使用 AJAX (jQuery),您可以在不刷新浏览器的情况下发布 XML 请求,如果这是您需要的。为此,只需创建一个带有一些文本字段和一个提交按钮的表单,为所有内容提供一个 ID 并为该按钮添加一个 click-Listener:

$('#submit-button').click(function() {
    var name = $('#username').val();
    $.ajax({
        type: 'POST',
        url: 'php_file_to_execute.php',
        data: {username: name},
        success: function(data) {
            if(data == "1") {
                document.write("Success");   
            } else {
                document.write("Something went wrong");
            }
        }
    });
});

如果用户单击具有“提交按钮”-ID 的按钮,则调用此函数。然后使用 POST 将文本字段的值发送到 php_file_to_execute.php。在这个 .php 文件中,您可以验证用户名并输出结果:

if($_POST['username'] != "Neha Raje") {
    echo "0";
} else {
    echo "1";
}

我希望我能帮助你!:)

于 2012-05-22T05:03:38.560 回答
0

使用 jQuery 的$.post()方法为:

$('#my_submit_button').click(function(event){
  event.preventDefault();
  var username = $('#username').val();
  $.post('validate.php', {username: username, my_submit_button: 1}, function(response){
   console.log(response); //response contain either "true" or "false" bool value 
  });
});

在 validate.php 中异步获取表单中的用户名,如下所示:

if(isset($_POST['my_submit_button']) && $_POST['my_submit_button'] == 1 && isset($_POST['username']) && $_POST['username'] != "") {

  // now here you can check your validations with $_POST['username']
  // after checking validations, return or echo appropriate boolean value like:
  // if(some-condition) echo true;
  // else echo false;

}

注意:在使用 AJAX 执行数据库更改脚本之前,请考虑了解与安全相关的漏洞和其他问题。

于 2012-05-22T05:42:48.483 回答
0

你可能想改写你写的东西,它有点不清楚。仅供参考,我这样做;

<form method="post">
Text 1: <input type="text" name="form[text1]" value="<?=$form["text1"]?>" size="5" /><br />
Text 2: <input type="text" name="form[text2]" value="<?=$form["text2"]?>" size="5" /><br />
<input type="submit" name="submit" value="Post Data" />
</form>

而当我处理数据的时候,是这样的;

<?php
if ($_POST["submit"]) {
 $i = $_POST["form"];
 if ($i["text1"] or ..... ) { $error = "Something is wrong."; }
 if ($i["text2"] and ..... ) { $error = "Maybe right."; }

 if (!$error) {
  /*
   * We should do something here, but if you don't want to return to the same
   * form, you should definitely post a header() or something like that here.
   */
   header ("Location: /"); exit;
 }
 //
}

if (!$_POST["form"] and !$_GET["id"]) {
} else {
 $form = $_POST["form"];
}
?>

通过这种方法,值不会丢失,除非您将它们设置为丢失。

于 2012-05-22T05:26:37.243 回答