使用Ajax提交2种不同的PHP表单 [英] Submit to 2 different PHP forms using Ajax
本文介绍了使用Ajax提交2种不同的PHP表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我想使用2个不同的PHP页面发送2个具有不同值的表单时,我遇到了问题.
I am facing issues when I want to send 2 forms with different values using 2 different PHP pages.
我的ajax代码如下:
My ajax code like this:
$(document).ready(function() {
var form = $('#main_form_new');
var submit = $('.sbbtn');
var alert = $('.form_result');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'ajax/category.php',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function() {
alert.fadeOut();
submit.html('Saving Changes....');
},
success: function(data) {
alert.html(data).fadeIn();
form.trigger('reset'); // reset form
submit.html('Save Changes');
},
error: function(e) {
console.log(e)
}
});
});
});
对于第二种形式,我更改了var并将其替换为
For the second form I changed the var and replaced it as
var itemform = $('#item_main_itemform_new');
var itemsubmit = $('.itemsbbtn');
var itemalert = $('.item_itemform_result');
itemform.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'ajax/items.php',
type: 'POST',
dataType: 'html',
data: itemform.serialize(),
beforeSend: function() {
itemalert.fadeOut();
itemsubmit.html('Saving Changes....');
},
success: function(data) {
itemalert.html(data).fadeIn();
itemform.trigger('reset'); // reset itemform
itemsubmit.html('Save Changes');
},
error: function(e) {
console.log(e)
}
});
});
这不起作用,因为我真的不知道原因.我在哪里做错了?
This does not work as I really do not know the reason. Where am I doing wrong?
推荐答案
不要重复自己.
如果两次需要相同的功能,请不要复制和粘贴代码.创建一个函数,对变量部分使用变量,然后两次调用该函数.
If you need the same functionality twice, don't copy and paste your code. Make a function, use variables for the variable parts, call that function twice.
$(function() {
function formSubmitHandler(options) {
return function (e) {
var $form = $(this),
$submit = $(options.submit),
$alert = $(options.alert);
e.preventDefault();
$alert.fadeOut();
$submit.html('Saving Changes...').prop({disabled: true});
$.post(options.url, $form.serialize())
.done(function (data) {
$alert.html(data).fadeIn();
$form.trigger('reset');
})
.fail(function (jqXHR, textStatus, errorThrown) {
$alert.html(textStatus).fadeIn();
console.log(arguments);
})
.always(function () {
$submit.html('Save Changes').prop({disabled: false});
});
};
}
$('#main_form_new').submit(formSubmitHandler({
url: 'ajax/category.php',
submit: '.sbbtn',
alert: '.form_result'
}));
$('#item_main_itemform_new').submit(formSubmitHandler({
url: 'ajax/items.php',
submit: '.itemsbbtn',
alert: '.item_itemform_result'
}));
});
这篇关于使用Ajax提交2种不同的PHP表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文