简体   繁体   English

如何使用Jquery的AJAX提交复杂的表单?

[英]How to submit a complex form using Jquery's AJAX?

I'm trying to submit a form using Jquery's ajax. 我正在尝试使用Jquery的ajax提交表单。 It has got a few textboxes, some checkboxes, and a multiple options' dropdown (ie multiple options can be selected). 它有一些文本框,一些复选框和多个选项的下拉菜单(即可以选择多个选项)。

Someone here told me that I can get values of all selected checkboxes using 这里有人告诉我,我可以使用所有选中的复选框的值

$("input:checkbox[name=type]:checked")

Then I can loop through all the values returned by the above code, assign them to an array like this: 然后我可以遍历上面代码返回的所有值,将它们分配给这样的数组:

var types=new Array();

    $.each(cboxes, function()
      {
         types[types.length]=$(this).val();
      }
    );

And try to submit the form using this: 并尝试使用以下方式提交表单:

var someField=$("#someField").val();
var someField2=$("#someField2").val();
var data={field1 : someField, field2=someField2, s_types:types};
$.post("signup.php?type=p",types);

But that doesn't work, specifically the checkboxes don't get submitted correctly. 但这不起作用,特别是复选框无法正确提交。 How can I make it work? 我怎样才能使它工作?

It's not necessary to iterate over each field to get the form values. 没有必要迭代每个字段来获取表单值。 jQuery has a method to serialize form inputs into a querystring. jQuery有一个方法将表单输入序列化为查询字符串。 You can do this: 你可以这样做:

$.ajax({
  url: "mybackend.php",
  data: $("#myForm").serialize(),
  success: function(e) { // do something on success },
  error: function(e) { // do something on error }
});

Remember that javascript posts always send data in UTF-8 format, so be sure you're expecting that on the backend if you plan to send text with international characters. 请记住,javascript帖子总是以UTF-8格式发送数据,因此如果您计划发送带有国际字符的文本,请确保在后端期望这样做。

I recommend using a plug-in to do that. 我建议使用插件来做到这一点。 Have a look at this form plug-in . 看看这个表单插件 It also can integrate nicely with validation plug-in . 它还可以与验证插件很好地集成。

The default jQuery $.param doesn't handle arrays ( by design ), so you can't use $.serialize as it is. 默认的jQuery $ .param不处理数组( 按设计 ),因此你不能使用$ .serialize。 Use either a plugin, like suggested in kgiannakis' answer , or overwrite the $.param function so it'll handle arrays properly: 使用插件,如kgiannakis的回答中建议的那样 ,或覆盖$ .param函数,以便它正确处理数组:

function($) {
  $.param = function(a) {
    var s = [];
    if (a.constructor == Array || a.jquery) 
      jQuery.each(a, function() { s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) ); });
    else
      for (var j in a)
        if (a[j] && a[j].constructor == Array) jQuery.each( a[j], function(){ s.push( encodeURIComponent(j) + "[]=" + encodeURIComponent( this ) ); });
        else s.push(encodeURIComponent(j) + "=" + encodeURIComponent(a[j]));
    return s.join("&").replace(/%20/g, "+");
  };
})(jQuery);

...and then use $.serialize, like suggested by Danita . ...然后使用$ .serialize,就像Danita建议的那样

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

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