我的Ajax为php发送了两次帖子
当我发送create.php以顺利上传时,我的表上不断出现两篇帖子我的Ajax为php发送了两次帖子,php,jquery,ajax,post,Php,Jquery,Ajax,Post,当我发送create.php以顺利上传时,我的表上不断出现两篇帖子 $(document).ready(function () { /* Data Insert Starts Here */ $(document).submit('submit', '#SavePost', function () { $.post("create.php", $(this).serialize()) .done(function (data) { $("#di
$(document).ready(function () {
/* Data Insert Starts Here */
$(document).submit('submit', '#SavePost', function () {
$.post("create.php", $(this).serialize())
.done(function (data) {
$("#dis").fadeOut();
$("#dis").fadeIn('slow', function () {
$("#dis").html('<div class="alert alert-info">' + data + '</div>');
$("#SavePost")[0].reset();
$("body").fadeOut('slow', function () {
$("body").fadeOut('slow');
window.location.href = "index.php";
});
});
});
/* Image upload Ajax */
$.ajax({
url: "create.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function (data) {
if (data == 'invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#SavePost")[0].reset();
}
},
error: function (e) {
$("#err").html(e).fadeIn();
}
});
/* Image upload Ajax ENDING */
return false;
});
/* Data Insert Ends Here */
$(文档).ready(函数(){
/*数据插入从这里开始*/
$(文档).submit('submit','#SavePost',函数(){
$.post(“create.php”,$(this.serialize())
.完成(功能(数据){
$(“#dis”).fadeOut();
$(“#dis”).fadeIn('slow',function(){
$(“#dis”).html(“”+数据+“”);
$(“#SavePost”)[0]。重置();
$(“body”).fadeOut('slow',function(){
$(“主体”)。淡出(“缓慢”);
window.location.href=“index.php”;
});
});
});
/*图像上传Ajax*/
$.ajax({
url:“create.php”,
类型:“POST”,
数据:新表单数据(本),
contentType:false,
cache:false,
processData:false,
beforeSend:函数(){
//$(“#预览”).fadeOut();
$(“#err”).fadeOut();
},
成功:功能(数据){
如果(数据=='无效文件'){
//无效的文件格式。
$(“#err”).html(“无效文件!”).fadeIn();
}否则{
//查看上传的文件。
$(“#预览”).html(数据).fadeIn();
$(“#SavePost”)[0]。重置();
}
},
错误:函数(e){
$(“#err”).html(e.fadeIn();
}
});
/*图像上传Ajax结束*/
返回false;
});
/*数据插入到此结束*/
我收到一个上传了图片的帖子,一个没有。我试着检查我的帖子是否被发送了两次,我试着删除了几行,但我似乎无法理解这一行
谢谢!很可能您正在使用
按钮
或提交
来触发ajax事件
您只需添加e.preventDefault();
试着这样使用:
$('#myForm').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function( response ) {
console.log( response );
}
});
return false;
});
$.post
和$.ajax
是两个独立的请求,因此您将发送两个请求,第一个请求通过$.post
方法发送,然后使用$.ajax
发送另一个请求。删除其中一个请求,您将只收到预期的一个请求。我的ajax正在发送post tphp的wice:this$.post(“create.php”,this.serialize())
和$.ajax({url:“create.php”,
)是什么?你会得到2,因为你发送了两次。一次使用$.post
,第二次使用$.ajax
,你做错了,$.post
和$.ajax
(几乎)同样的!#exportForm
在哪里?您是如何处理这两个请求的?感谢Tobias!我删除了第一部分并保留了Ajax。我发现我需要更改提交函数..提交到.上的('submit','#SavePost',函数()