我有一个名为orderproductForm的表单和未定义数量的输入。
我想用jQuery。get或ajax或类似的东西会通过ajax调用一个页面,并发送orderproductForm表单的所有输入。
我想有一种方法是
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
然而,我不知道确切地所有表单输入。是否有一个特性,功能或一些东西,只是发送所有的表单输入?
我知道这是一个与jQuery相关的问题,但现在使用JS ES6的事情要容易得多。由于没有纯javascript的答案,我想我可以添加一个简单的纯javascript解决方案,这在我看来是更干净的,通过使用fetch() API。这是实现网络请求的一种现代方式。在您的例子中,由于已经有了表单元素,我们可以简单地使用它来构建我们的请求。
const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(form.action,
{
method: form.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
JavaScript
(function ($) {
var form= $('#add-form'),
input = $('#exampleFormControlTextarea1');
form.submit(function(event) {
event.preventDefault();
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data) {
if (data === 'success') {
var li = $('<li class="list-group-item">'+ input.val() +'</li>');
li.hide()
.appendTo('.list-group')
.fadeIn();
$('input[type="text"],textarea').val('');
}
});
});
}(jQuery));
HTML
<ul class="list-group col-sm-6 float-left">
<?php
foreach ($data as $item) {
echo '<li class="list-group-item">'.$item.'</li>';
}
?>
</ul>
<form id="add-form" class="col-sm-6 float-right" action="_inc/add-new.php" method="post">
<p class="form-group">
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="Is there something new?"></textarea>
</p>
<button type="submit" class="btn btn-danger">Add new item</button>
</form>
Try
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We submit form asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)" name="orderproductForm">
<input hidden name="csrfToken" value="$0meh@$h">
<input name="email" value="aa@bb.com">
<input name="phone" value="123-456-666">
<input type="submit">
</form>
Look on Chrome Console > Network after/before 'submit'
你可以使用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序列化文档在这里。