简体   繁体   English

jquery .serialize() 不适用于动态加载的表单

[英]jquery .serialize() does not work on dynamically loaded form

I have a form which is submitted via ajax triggered by an image click, after the form is submitted it is returned and reloaded.我有一个通过图像点击触发的ajax提交的表单,提交表单后它被返回并重新加载。 However the .serialize() has stopped working.但是 .serialize() 已停止工作。

here is some code:这是一些代码:

<form id="myForm" action="/someFormSubmitPage.do">
    <div id="myFormQuestions">
        <input type="text" name="fred"/>
        <!--more inputs-->
    </div>
 <img id="submitButton" src="some/path">
</form>

image of the submit button triggers via .click in jquery the below function提交按钮的图像通过 .click 在 jquery 下面的函数中触发

var serializedForm = $("#myForm").serialize();
$.post("/someFormSubmitPage.do", serializedForm, function( data ) {
    //do some stuff with the data
    $( "#myFormQuestions" ).html(data);
});

this works fine on the first submit, but on the second, the var serialized form ends up as an empty string despite the user repopulating the inputs这在第一次提交时工作正常,但在第二次提交时,尽管用户重新填充了输入,但 var 序列化的表单最终还是一个空字符串

EDIT: I have now included a JSFiddle , however, im not sure how to use the ajax tesing echo thing.编辑:我现在已经包含了一个JSFiddle ,但是,我不确定如何使用 ajax tesing echo 的东西。

Can you check out what response are coming back? 你能看看回复的回复吗? Cause I think that it's the problem with DOM elements identification. 因为我认为这是DOM元素识别的问题。 The problem could be something like that: 问题可能是这样的:

You have two elements matching $('#myForm') selector, and jQuery got lost. 你有两个匹配$('#myForm')选择器的元素,jQuery丢失了。 Try to modify this selector with $('form#myForm') . 尝试使用$('form#myForm')修改此选择器。 Try it, and post here what you have in response. 尝试一下,然后在这里发布您的回复。

Now, I've checked if it's work fine, the code is: 现在,我已经检查过它是否正常工作,代码是:

<div>
    <form id="myForm">
        <div id="inputs">
            <input name="some" type="text" />
        </div>
        <input type="button" id="my-form-submit" value="submit" />
    </form>

</div>
<script type="text/javascript">
    $('input#my-form-submit').on('click', function(e) {
        var data = $('form#myForm').serialize();
        $.post('/test.php', data, function(response) {
            $('div#inputs').html($(response).find('div#inputs'));
        });
    });
</script>

And that's work fine, each time on submit page post to itself, then in response search for inputs and places inputs into form inputs dir. 这样做工作正常,每次提交页面发布到自己,然后在响应中搜索输入并将输入放入表单输入目录。

As an aside, but while I have seen JSFiddle a couple times but didn't know what it was, I followed the link and WOW, what a great development aid! 顺便说一句,虽然我已经看过JSFiddle几次但不知道它是什么,我跟着链接和WOW,这是一个很棒的开发辅助工具! I'm definitelyAA adding this one to my toolbox! 我绝对是把这个添加到我的工具箱中!

I modified the code to dynamically add another text input filed to the form, every time the submit button is clicked you get yet another dynamically added input ( with dynamically name 'name' and id ) and the alert reports all the named elements in the form. 我修改了代码以动态地将另一个文本输入字段添加到表单中,每次单击提交按钮时,您将获得另一个动态添加的输入(动态名称为“name”和id),并且警报报告表单中的所有命名元素。

I didn't know that you needed to define the name attribute for an item to serialize! 我不知道你需要为要序列化的项定义name属性!

Here is my Fiddle : jsfiddle dynamically form and serialize 这是我的小提琴: jsfiddle动态形式和序列化

In aspx page: 在aspx页面中:

<form id="myForm" action="">
<div id="myQuestions">
    <input type="text" name="entryOne"/>
</div>


Click the logo to submit the form 单击徽标以提交表单

In JQuery Enabled JavaScript: 在JQuery Enabled JavaScript中:

var counter = 0;

$(function(){
    $("#submitImage").click(function(){
        startAjaxFormSubmit();
    });
    //there is also another even that calls startAjaxFormSubmit
});


function startAjaxFormSubmit() {
    alert("startAjaxFormSubmit");
    var serializedForm = $("#myForm").serialize();
    alert("serializedForm is:\n=====\n"+serializedForm +"\n=====");

    $.post("/echo/html", serializedForm, function(data) {
        //do something with the data
        $("#myQuestions").append(data);

    });

    var div = $("#myQuestions");
    var $dynalabel = $('<br/>"<label>').text("Dynamic Input " + counter + ": ");
    div.append($dynalabel);
    var $dynaInput = $('<input type="text" name="dynaName_' + counter + '" id="id_' + counter + '"/>');
    div.append($dynaInput);
    counter++;
}

I had the same problem and fixed it by calling "remove", and then "appendTo" 我有同样的问题并通过调用“删除”,然后“appendTo”修复它

var serializedForm = $ ("# myForm").serialize();
$ .post ("/someFormSubmitPage.do" serializedForm, function (data) {
    
     $ ("#myFormQuestions").remove();
     $ (data).appendTo('#myFormQuestions');
});

I am adding this to help others, bootstrap examples often don't use the name tags in the input fields.我添加这个是为了帮助其他人,引导程序示例通常不使用输入字段中的名称标签。 This caught me out and I was wondering why I couldn't serialize the data from my form.这引起了我的注意,我想知道为什么我不能从我的表单中序列化数据。 Simply put ensure you have name tags in your input fields.简单地说,确保您的输入字段中有名称标签。

So, I guess the complete form is replaced with newer HTML upon the Ajax-request? 那么,我想在Ajax请求时,完整的表单会被更新的HTML替换掉? In that case you could reload the entire div the form is located in, so that the event handlers are binded again when the form is reloaded. 在这种情况下,您可以重新加载表单所在的整个div,以便在重新加载表单时再次绑定事件处理程序。 eg: 例如:

<div id="myFormDiv">
     <form id="myForm" onsubmit="myAjaxCall(this)">
     <!-- inputs-->
     </form>
     <img onclick="$('#myForm').submit()"/>
</div>

<!-- javascript-->
function myAjaxCall(form){
     serializedForm = $(form).serialize();
     $('#myFormDiv').load('/submitpage.php'),{formdata:serializedForm}, function(data)(){});
}

Or, ofcourse, if you say that it is not done on submit you can do <img onclick="myAjaxCall($('#myForm'))" 或者,当然,如果你说它没有在提交时完成,你可以做<img onclick="myAjaxCall($('#myForm'))"

If the missing double quote after ' type="text ' is not just a typo in your post but also your actual HTML in the server response (not the intitial page HTML though since the first call to serialize() seems to work), it's probably what's causing the problem. 如果'type =“text'之后缺少的双引号不仅仅是你帖子中的拼写错误,而且还是你服务器响应中的实际HTML(虽然自第一次调用serialize()以来就不是真正的HTML页面,但是它是可能是什么导致了这个问题。


Fiddle with double quote added: 添加双引号的小提琴:

http://jsfiddle.net/dCDwB/ http://jsfiddle.net/dCDwB/


And without it: 没有它:

http://jsfiddle.net/dCDwB/2/ http://jsfiddle.net/dCDwB/2/

(see console, it sends "fred+value%3D=" rather than "fred=") (见控制台,它发送“fred + value%3D =”而不是“fred =”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM