jQuery AJAX submit form
I have a form with name orderproductForm
and an undefined number of inputs.
I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm
.
I suppose one way would be to do something like
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?
You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.
AjaxForm :
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
or
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.
Serialize :
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theForm').serialize())
AJAX serialization documentation is here.
This is a simple reference:
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I hope it helps you.
使用表单元素上定义的属性的另一个类似的解
<form id="contactForm1" action="/your_url" method="post">
<!-- Form input fields here (do not forget your name attributes). -->
</form>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
链接地址: http://www.djcxy.com/p/9506.html
上一篇: jQuery Ajax文件上传
下一篇: jQuery AJAX提交表单