简体   繁体   English

jQuery:在序列化之前保留表单值?

[英]jQuery: Persisting form values before serialize?

I am using jQuery serialize() function to collect data in a form and submit to server using jQuery Ajax "post" method, like this: var params = jQuery('#mainContent form').serialize(); 我使用jQuery serialize()函数来收集表单中的数据并使用jQuery Ajax“post”方法提交给服务器,如下所示: var params = jQuery('#mainContent form').serialize(); .
The strange thing I saw is the serialized data from my form contains old data. 我看到的奇怪的事情是我的表单中的序列化数据包含旧数据。 It means, all of my changes in form (input to text-field, select on combo-box) is not stored to DOM, so when jQuery call serialize() , it collect the old data which appeared before I change the form. 这意味着,我在表单中的所有更改(输入到文本字段,在组合框中选择)都不会存储到DOM,因此当jQuery调用serialize() ,它会收集在更改表单之前出现的旧数据。 I tried to inspect to each element in that form and call .val() , it still showed the old values. 我试图检查该表单中的每个元素并调用.val() ,它仍然显示旧值。
So how can I persist all my changes to form, that the serialize() method can build the string with newest data I entered? 那么我怎么能坚持我的所有变化形式, serialize()方法可以用我输入的最新数据构建字符串?
Here is my snippet code, I called serialize() inside submit handler 这是我的代码段代码,我在提交处理程序中调用了serialize()

jQuery('.myFormDiv input.submit').click(function() {  
    // Do something  
    // Collect data in form  
    var params = jQuery('#mainContent form').serialize();  
    // Submit to server  
    jQuery.post(url, params, successHandler);  
}

Thank you so much. 非常感谢。

When are you calling serialize? 你什么时候打电话给序列化? it should be $('form').submit( [here] ); 它应该是$('form')。submit([here]); It sounds like it's being called on page load, before you enter values into the fields, then being used after. 听起来它是在页面加载时被调用,然后在字段中输入值,然后在之后使用。

EDIT: 编辑:

using the submit event instead of on click will catch someone hitting enter in a text field. 使用提交事件而不是点击将捕获某人在文本字段中输入。

jQuery('#mainContent form').submit(function() {  
  // Collect data in form  
  var params = jQuery(this).serialize();  
  // Submit to server  
  jQuery.post(url, params, successHandler);  
}

*the above code assume url is define and successHandler is a function. *上面的代码假设url是define,successHandler是一个函数。

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

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