我有一个名为orderproductForm的表单和未定义数量的输入。
我想用jQuery。get或ajax或类似的东西会通过ajax调用一个页面,并发送orderproductForm表单的所有输入。
我想有一种方法是
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
然而,我不知道确切地所有表单输入。是否有一个特性,功能或一些东西,只是发送所有的表单输入?
这段代码甚至可以使用文件输入
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
你也可以使用FormData(但在IE中不可用):
var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector
$.ajax({
type: "POST",
url: "yourURL",// where you wanna post
data: formData,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
},
success: function(data) {console.log(data)}
});
这就是如何使用FormData。
你可以使用Ajax Form Plugin或jQuery serialize函数中的ajaxForm/ajaxSubmit函数。
AjaxForm:
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
or
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
当按下提交按钮时,ajaxForm将发送。ajaxSubmit立即发送。
序列化:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theForm').serialize())
AJAX序列化文档在这里。
我觉得很奇怪,没有人提到数据是一个对象。对我来说,这是传递数据最干净、最简单的方式:
$('form#foo').submit(function () {
$.ajax({
url: 'http://foo.bar/some-ajax-script',
type: 'POST',
dataType: 'json',
data: {
'foo': 'some-foo-value',
'bar': $('#bar').val()
}
}).always(function (response) {
console.log(response);
});
return false;
});
然后,在后端:
// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
这不是OP问题的答案,
但如果你不能使用静态形式的DOM,你也可以这样尝试。
var $form = $('<form/>').append(
$('<input/>', {name: 'username'}).val('John Doe'),
$('<input/>', {name: 'user_id'}).val('john.1234')
);
$.ajax({
url: 'api/user/search',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $form.serialize(),
success: function(data, textStatus, jqXHR) {
console.info(data);
},
error: function(jqXHR, textStatus, errorThrown) {
var errorMessage = jqXHR.responseText;
if (errorMessage.length > 0) {
alert(errorMessage);
}
}
});