jquery.load() POST 表单的所有元素,而不必指定要 POST 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9318372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:38:48  来源:igfitidea点击:

jquery.load() to POST all elements of a form rather than having to specify what to POST

ajaxjquery

提问by Joe M.

I have an existing HTML form that I'm trying to update to use jQuery.load(). How can I pass all of the elements of the form as POST parameters rather than having to specify which parameters to pass?

我有一个现有的 HTML 表单,我正在尝试更新它以使用 jQuery.load()。如何将表单的所有元素作为 POST 参数传递,而不必指定要传递的参数?

The form elements are created dynamically by a script and the number of elements as well as the name of the elements varies considerably to the extent that it's not practical to specify which parameters to pass via AJAX/POST. Is there a simple way to pass to jQuery.load() all of the elements within the <form></form>tags as if the form was submitted traditionally?

表单元素是由脚本动态创建的,元素的数量以及元素的名称变化很大,以至于指定通过 AJAX/POST 传递哪些参数是不切实际的。是否有一种简单的方法可以将<form></form>标签中的所有元素传递给 jQuery.load(),就好像表单是传统提交的一样?

回答by Rose Perrone

Easy: When you gather your form data and past it as the second parameter to load(), use serializeArray(data), and don't use serialize(data), as the currently accepted answer recommends.

简单:当您收集表单数据并将其作为第二个参数传递给 时load(),使用serializeArray(data)和不使用serialize(data),正如当前接受的答案所建议的那样。

serialize()returns a string, whereas serializeArray()returns an object. load()sends a POST if the data is an object. If data is a string, load()sends a GET.

serialize()返回一个字符串,而serializeArray()返回一个对象。 load()如果数据是对象,则发送 POST。如果数据是字符串,则load()发送 GET。

回答by derekaug

You can use .serialize()to serialize all of the inputs of the form for submitting along with your jQuery.load() call.

您可以使用.serialize()序列化表单的所有输入与您的 jQuery.load() 调用一起提交。

$('form').serialize()

For example, using jQuery.load()(only does GET unless you pass it an object for data, then POST)

例如,使用jQuery.load()(只有 GET 除非您将数据对象传递给它,然后是 POST)

$.load(
    'postTo.php', 
    $('#yourFormId').serialize(), 
    complete(responseText, textStatus, XMLHttpRequest){
        //do your processing after the fact
}))

Using, jQuery.ajax(), you can make it POST

使用, jQuery.ajax(),您可以将其设为 POST

$.ajax({
    'url': 'postTo.php',
    'type': 'POST',
    'data': $('#yourFormId').serialize(),
    'success': function(result){
         //process here
    }
});

See: http://api.jquery.com/jQuery.ajax/

请参阅:http: //api.jquery.com/jQuery.ajax/