使用ajax + jquery嵌套表单提交帮助

时间:2010-12-31 02:10:10

标签: javascript jquery ajax

我是jquery和ajax的新手,下面的代码在提交表单的第二次尝试后无效...继承人javascript代码:

        $(document).ready(function() { 
        var options = { 
        target:        '#output2',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse  // post-submit callback 

        }; 

        $('#myForm2').submit(function() {



        $(this).ajaxSubmit(options); 
        return false; 
        });

 $('#me').submit(function() {
        $("#div2").load("main.php"); 
        return false; 
        }); 
    }); 
    function showRequest(formData, jqForm, options) { 
    return true; 
    } 
    function showResponse(responseText, statusText, xhr, $form)  {}

顺便说一句,我使用jquery表单插件.....

和index.php

<form id="me" action="" method="post">
Message: <input type="text" name="mess">
<input type="submit" value="submit">

最后为main.php

<form id="myForm2" action="index.php" method="post"><div>

                    Name:</td><td><input name="Name" type="text" />

                    <input type="reset"   name="resetButton " value="Reset" />

                    <input type="submit"  name="submitButton" value="Submit1" />



            </div></form>

            <h1>Output Div (#output2):</h1>

            <div id="output2">AJAX response will replace this content.</div>

        </div>

2 个答案:

答案 0 :(得分:1)

您在页面加载后下载表单(* $(“#div2”)。load(“main.php”))并且您的事件已经绑定。因此,当您的第二个表单加载时,它的提交按钮单击事件不会消除任何内容。你必须在jQuery here

中阅读.live()

这是我的解决方案(这只是简单的例子):

$('#myForm2').live("click",function() {
    $(this).ajaxSubmit(options); 
    return false; 
});

也许这对你有用。

UPD

你也可以试试这个:

1)替换

$('#myForm2').live("click",function() {
    $(this).ajaxSubmit(options); 
    return false; 
});

function MyFormSubmit(form) {
    $(form).ajaxSubmit(options); 
    return false; 
})

2)向您添加JS代码myForm2提交按钮onClick事件

    <form id="myForm2" action="index.php" method="post"><div>

                Name:</td><td><input name="Name" type="text" />

                <input type="reset"   name="resetButton " value="Reset" />

                <input type="submit"  name="submitButton" value="Submit1"
                 onClick="javascript:MyFormSubmit(this);return false;"/>



        </div></form>

        <h1>Output Div (#output2):</h1>

        <div id="output2">AJAX response will replace this content.</div>

    </div>

答案 1 :(得分:0)

您必须从表单中删除action="index.php" method="post"。那应该有用吗。

因为现在它仍然将php发布到index.php