使用Ajax重新加载表单


Reloading Forms With Ajax

我有生成表单的PHP代码。我希望在用户单击提交按钮后能够使用Ajax重新加载表单。这应该会重新加载用户刚刚输入的表单。我有这样的代码:

PHP:

<?php
$html = <<<HTML
<form id="myform" method="post">  
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="name" size="30" value=""/>  
    <br>
    <input type="submit" name="submit" value="Submit"> 
</form>
HTML;
echo $html;
echo rand(1, 10);
?>

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html>
<head>
    <title>JQuery Form Example</title> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#myform").validate({
            debug: false,
            rules: {
                name: "required",
            },
            messages: {
                name: "Please fill in answer.",
            },
            submitHandler: function(form) {
                // do other stuff for a valid form
                $.post('process.php', $("#myform").serialize(), function(data) {
                    $('#results').html(data);
                });
            }
        });
    });
    </script>
    <style>
    label.error { width: 250px; display: inline; color: red;}
    </style>
</head>
<body>
<div id="results">
<?php require_once('process.php'); ?>
</div>
</body>
</html>

不幸的是,使用一次后,整个页面将重新加载。我发现解决这个问题的唯一方法是将<?php require_once('process.php'); ?>放在<div id="results">之外,这会导致出现两种形式。有什么办法解决这个问题吗?此外,我使用这个jquery插件:http://jqueryvalidation.org/

用从PHP后端获得的新表单替换表单后,表单失去了EventListener。

因此,您必须重新初始化插件(在从AJAX帖子中获得新表单后再次调用$("#myform").validate({});),或者将事件侦听器设置为父DOM元素(例如,将表单包装在<div id="form-container">..</div>中)并替换容器的内容。

在JS中尝试以下操作:

$("#results").on('submit', '#myform', function(e) {
   e.preventDefault();
   $("#myform").validate({
        debug: false,
        rules: {
            name: "required",
        },
        messages: {
            name: "Please fill in answer.",
        },
        submitHandler: function(form) {
            // do other stuff for a valid form
            $.post('process.php', $("#myform").serialize(), function(data) {
                $('#results').html(data);
            });
        }
    });
    return false;
  });

编辑:刚刚看到您使用的是jQuery 1.4.2。要使用on(),您必须至少包含jQuery 1.7,或者使用live():

$("#results").live('#myform', 'submit', function(e) { //the rest of your stuff });

使用jqueryForm插件。之后,您可以使用ajaxSubmit。Jquery表单插件