【问题标题】:Page reloads even after return false in ajax $.post request即使在 ajax $.post 请求中返回 false 后页面也会重新加载
【发布时间】:2017-04-14 18:35:17
【问题描述】:

我正在尝试使用 ajax 调用提交表单后上传图像,遇到一个让我烦恼的问题,新的 FormData($(this)[0]) 给了我实际值,但是每当我尝试通过 ajax 发送它时,它就会出现故障并重新加载页面,所以我也看不到控制台,请纠正我的错误。

我的 javascript 代码

$("#editImage").submit(function(){
var data = new FormData($(this)[0]);
console.log(data);
return false;
$.post("../galImages", data).done(function(response){
    console.log(response);
});
return false;});

我的 HTML 代码

<form name="edit-image" id="editImage" action="" method="post" enctype="multipart/form-data"><input type="file" name="change-image" accept="image/*" class="form-control mb-20" value="Upload Image">
                    <input type="hidden" name="edit-img-id" id="editImageId"><input type="submit" class="btn btn-primary" value="Save Changes" id="submitEditImgForm"></form>

但是文件数据是在 PHP 页面中发布的,还有一件事是如何将隐藏字段值与 formdata 对象一起发送。我是 ajax $.post 方法的新手。如果有人有任何想法,请帮助我。

【问题讨论】:

  • 在 jQuery .submit 中,您应该阻止处理表单/数据的默认行为吗?表单(其中的目标网址)呢?
  • @OldPadawan 我已经更新了 html 部分
  • 那么,我猜preventDefault 会这样做
  • 现在抛出 Illegal invocation

标签: php jquery ajax


【解决方案1】:

当您上传图片时(我的错误,首先忘记了!): 重要的部分是needed for upload 否则会失败

$(function () {
$('#my_form').on('submit', function (e) {
    e.preventDefault();

    var $form = $(this);
    var formdata = (window.FormData) ? new FormData($form[0]) : null;
    var data = (formdata !== null) ? formdata : $form.serialize();

    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'),
        contentType: false, // needed for upload
        processData: false, // needed for upload
        dataType: 'json', // return
        data: data,
        success: function (response) {
            // response
        }
     });
   });
});

这段代码不是我的,找到的,很久以前改编的,不能相信它的原始所有者,因为我不记得她/他是谁:/

【讨论】:

  • 欢迎您。未来的好代码,对于“给”我们这部分代码但不会因此获得荣誉的伙伴感到抱歉......
【解决方案2】:

使用preventDefault() 这将防止表单和页面的默认行为重新加载。

$("#editImage").submit(function (e) {
    e.preventDefault();
    var data = new FormData($(this)[0]);
    console.log(data);
    return false;
    $.post("../galImages", data).done(function (response) {
        console.log(response);
    });
    return false;
});

【讨论】:

  • 谢谢@julekgwa,看起来它的工作正常,页面停止重新加载但console.log 中有一个错误Illegal invocation,阻止页面将数据发送到目标php 文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多