dongqiangteng7319 2014-01-01 02:46 采纳率: 0%
浏览 365
已采纳

使用jQuery在AJAX请求后停止重定向

I'm trying to get a simple form to submit via AJAX to the submit.php page where it is sent to a database. When I submit it, it redirects to submit.php. I want it to submit without redirecting. Thanks in advance!

JS

var request;
$("#myForm").submit(function(event){
    if (request) {
        request.abort();
    }
    var $form = $(this);
    var $inputs = $form.find("input, select, button, textarea");
    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);
    request = $.ajax({
        url: "/submit.php",
        type: "post",
        data: serializedData

        //Could something like this work? 
        //complete: function() {***Stop redirect?***}



    });

    request.done(function (response, textStatus, jqXHR){
        console.log("Hooray, it worked!");
    });

    request.fail(function (jqXHR, textStatus, errorThrown){
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });

    request.always(function () {
        $inputs.prop("disabled", false);
    });

    event.preventDefault();
});
  • 写回答

2条回答 默认 最新

  • dro44817 2014-01-01 03:33
    关注

    Is the document ready when your code runs? If not, $("#myForm") is returning an empty jQuery object, therefore any handlers attached to it won't ever be called. Test this by saving the jQuery object to a variable and logging it to the console.

    Two solutions:

    • Move your code into a document ready handler: $(function () { /* my code dependent on DOM elements */ });
    • Use an event listener instead of binding to elements: $(document).on('submit', '#myForm', function (event) { /* handler */ }

    There's nothing wrong with the event.preventDefault(); line - it can stay where it is, although I prefer to place it at the very top unless it's part of a conditional - and return false; isn't needed.

    Reason I can answer this: I just setup a local test for this and came across the same problem: my submit handler wasn't running at all. But then I realised my <script> tag was before the #myForm element but my code wasn't waiting until #myForm was in the document before trying to find it with $().

    Edit: Placing the <script> tag at the bottom of the <body> negates the need to wait for document ready in your case. It also speeds up page rendering, but that's a whole other discussion.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法