Nat*_*n H 886 javascript forms ajax jquery submit
我有一个名称orderproductForm
和未定义输入数量的表单.
我想做一些jQuery.get或ajax或类似的东西,它会通过Ajax调用页面,并发送表单的所有输入orderproductForm
.
我想有一种方法可以做类似的事情
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
Run Code Online (Sandbox Code Playgroud)
但是我并不完全知道所有表格输入.是否有功能,功能或其他东西只发送所有表单输入?
小智 1321
这是一个简单的参考:
// this is the id of the form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
Run Code Online (Sandbox Code Playgroud)
我希望它对你有所帮助.
jsp*_*cal 781
您可以使用Ajax Form Plugin中的ajaxForm/ajaxSubmit函数或jQuery serialize函数.
AjaxForm:
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
Run Code Online (Sandbox Code Playgroud)
要么
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
Run Code Online (Sandbox Code Playgroud)
当按下提交按钮时,ajaxForm将发送.ajaxSubmit立即发送.
序列化:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theForm').serialize())
Run Code Online (Sandbox Code Playgroud)
Dav*_*rdi 450
使用表单元素上定义的属性的另一个类似解决方案
<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>
Run Code Online (Sandbox Code Playgroud)
sup*_*ary 172
您需要记住一些事项.
1.提交表格有多种方法
因此,我们应该绑定到表单提交事件,而不是按钮单击事件.这将确保我们的代码现在和将来都适用于所有设备和辅助技术.
2. Hijax
用户可能未启用JavaScript.这里有一个hijax模式很好,我们使用JavaScript轻轻控制表单,但如果JavaScript失败则保持可提交.
我们应该从表单中提取URL和方法,因此如果HTML发生更改,我们就不需要更新JavaScript.
3.不引人注目的JavaScript
使用event.preventDefault()而不是return false是很好的做法,因为它允许事件冒泡.这使得其他脚本可以与事件相关联,例如可能正在监视用户交互的分析脚本.
速度
理想情况下,我们应该使用外部脚本,而不是插入内联脚本.我们可以使用脚本标记链接到页面的head部分,或者链接到页面底部以获得速度.该脚本应该悄然增强用户体验,而不是妨碍用户体验.
码
假设您同意上述所有内容,并且想要捕获提交事件,并通过AJAX(hijax模式)处理它,您可以执行以下操作:
$(function() {
$('form.my_form').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
});
Run Code Online (Sandbox Code Playgroud)
您可以随时通过JavaScript手动触发表单提交,例如:
$(function() {
$('form.my_form').trigger('submit');
});
Run Code Online (Sandbox Code Playgroud)
编辑:
我最近不得不这样做,最后写了一个插件.
(function($) {
$.fn.autosubmit = function() {
this.submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
return this;
}
})(jQuery)
Run Code Online (Sandbox Code Playgroud)
将data-autosubmit属性添加到表单标记,然后您可以执行以下操作:
<form action="/blah" method="post" data-autosubmit>
<!-- Form goes here -->
</form>
Run Code Online (Sandbox Code Playgroud)
$(function() {
$('form[data-autosubmit]').autosubmit();
});
Run Code Online (Sandbox Code Playgroud)
mac*_*Jun 40
您也可以使用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)}
});
Run Code Online (Sandbox Code Playgroud)
这就是您使用FormData的方式.
Tim*_*nen 27
<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
(function($){
$("body").on("submit", ".my-form", function(e){
e.preventDefault();
var form = $(e.target);
$.post( form.attr("action"), form.serialize(), function(res){
console.log(res);
});
});
)(jQuery);
</script>
Run Code Online (Sandbox Code Playgroud)
它是Alfrekjv答案的修改版本
JavaScript的
jQuery(document).submit(function(e){
var form = jQuery(e.target);
if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
e.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
我想编辑Alfrekjv的答案,但偏离了太多,所以决定将其作为一个单独的答案发布.
不发送文件,不支持按钮,例如单击按钮(包括提交按钮)将其值作为表单数据发送,但由于这是一个ajax请求,因此不会发送按钮单击.
要支持按钮,您可以捕获实际的按钮单击而不是提交.
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
在服务器端,您可以使用jquery
为php 设置的此标头检测ajax请求HTTP_X_REQUESTED_WITH
PHP
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is ajax
}
Run Code Online (Sandbox Code Playgroud)
Sha*_*lam 22
此代码甚至可以在文件输入时使用
$(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)
{
}
});
});
Run Code Online (Sandbox Code Playgroud)
Bru*_*ill 13
我真的很喜欢这个答案由superluminary的,尤其是他的包裹方式是解决方案的jQuery插件.所以感谢superluminary一个非常有用的答案.但就我而言,我想要一个插件,允许我在初始化插件时通过选项定义成功和错误事件处理程序.
所以这就是我提出的:
;(function(defaults, $, undefined) {
var getSubmitHandler = function(onsubmit, success, error) {
return function(event) {
if (typeof onsubmit === 'function') {
onsubmit.call(this, event);
}
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function() {
if (typeof success === 'function') {
success.apply(this, arguments);
}
}).fail(function() {
if (typeof error === 'function') {
error.apply(this, arguments);
}
});
event.preventDefault();
};
};
$.fn.extend({
// Usage:
// jQuery(selector).ajaxForm({
// onsubmit:function() {},
// success:function() {},
// error: function() {}
// });
ajaxForm : function(options) {
options = $.extend({}, defaults, options);
return $(this).each(function() {
$(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
});
}
});
})({}, jQuery);
Run Code Online (Sandbox Code Playgroud)
这个插件允许我非常轻松地"ajaxify"页面上的html表单,并提供onsubmit,成功和错误事件处理程序,以便向用户提供表单提交状态的反馈.这允许插件使用如下:
$('form').ajaxForm({
onsubmit: function(event) {
// User submitted the form
},
success: function(data, textStatus, jqXHR) {
// The form was successfully submitted
},
error: function(jqXHR, textStatus, errorThrown) {
// The submit action failed
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,成功和错误事件处理程序接收与jQuery ajax方法的相应事件相同的参数.
我为我得到了以下内容:
formSubmit('#login-form', '/api/user/login', '/members/');
Run Code Online (Sandbox Code Playgroud)
哪里
function formSubmit(form, url, target) {
$(form).submit(function(event) {
$.post(url, $(form).serialize())
.done(function(res) {
if (res.success) {
window.location = target;
}
else {
alert(res.error);
}
})
.fail(function(res) {
alert("Server Error: " + res.status + " " + res.statusText);
})
event.preventDefault();
});
}
Run Code Online (Sandbox Code Playgroud)
这假设帖子'url'以形式返回ajax {success: false, error:'my Error to display'}
您可以根据需要改变它.随意使用该片段.
jQuery AJAX提交表单,只需在单击按钮时使用表单ID提交表单
请按照步骤操作
第1步 - 表单标记必须具有ID字段
<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>
Run Code Online (Sandbox Code Playgroud)
您要点击的按钮
<button>Save</button>
Run Code Online (Sandbox Code Playgroud)
第2步 - 在jQuery中提交事件有助于提交表单.在下面的代码中,我们正在准备来自HTML元素名称的 JSON请求.
$("#submitForm").submit(function(e) {
e.preventDefault();
var frm = $("#submitForm");
var data = {};
$.each(this, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
$.ajax({
contentType:"application/json; charset=utf-8",
type:frm.attr("method"),
url:frm.attr("action"),
dataType:'json',
data:JSON.stringify(data),
success:function(data) {
alert(data.message);
}
});
});
Run Code Online (Sandbox Code Playgroud)
现场演示点击下面的链接
我知道这是一个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"));
Run Code Online (Sandbox Code Playgroud)
尝试
fetch(form.action,{method:'post', body: new FormData(form)});
Run Code Online (Sandbox Code Playgroud)
fetch(form.action,{method:'post', body: new FormData(form)});
Run Code Online (Sandbox Code Playgroud)
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We submit form asynchronously (AJAX)');
e.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)
考虑使用 closest
$('table+table form').closest('tr').filter(':not(:last-child)').submit(function (ev, frm) {
frm = $(ev.target).closest('form');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data);
}
})
ev.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以在提交功能上使用它,如下所示。
HTML 表单
<form class="form" action="" method="post">
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
</form>
Run Code Online (Sandbox Code Playgroud)
jQuery 函数:
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "POST",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
Run Code Online (Sandbox Code Playgroud)
欲了解更多详情和样本访问:http : //www.spiderscode.com/simple-ajax-contact-form/