美文网首页
jQuery Ajax 请求的 .done 方法在 chrom

jQuery Ajax 请求的 .done 方法在 chrom

作者: saronic | 来源:发表于2017-11-14 15:11 被阅读34次

代码很简单,发送 post,请求结束后执行 .done 或者 .always, 但是在 Chrome 和 Edge下,.done 和 .always 会运行,在 Firefox 下一直不能运行,代码如下:

function login() {
        var phone = $("#phone").val();
        var inputPassword = $("#inputPassword").val();
        $.ajax({
            url:'/login',
            type:'post',
            data: {phone: phone, pwd:inputPassword}
        })
            .done(function( data ) {
                alert(data.data);
            })
            .always(function (data) {
                alert("always here");
            });
    }

在网上查,发现需要提供 event,解决方法,在 button 调用 onClick handler 时候传入 evenet,变成:

<button class="btn btn-lg btn-primary btn-block" type="submit" onclick="login(event)">登录</button>

在 handler 函数里添加 event.preventDefault(); ,代码如下:

function login(event) {
        event.preventDefault();
        var phone = $("#phone").val();
        var inputPassword = $("#inputPassword").val();
        $.ajax({
            url:'/login',
            type:'post',
            data: {phone: phone, pwd:inputPassword}
        })
            .done(function( data ) {
                alert(data.data);
            })
            .always(function (data) {
                alert("always here");
            });
    }

You didn't define event as parameter of the event handler, hence in

event.preventDefault();

the browser tries to look up event in the global scope. Chrome happens to provide the event object in global scope (hence no error) but Firefox doesn't (hence an error).

I'd suggest to add the event parameter to the event handler:

$("#dodaj").click(function(event){
    event.preventDefault();
    // ...
});

There is an additional difference: If you don't define the event parameter, eventwill refer to the native event object in Chrome, which is different than the event object which jQuery passes to the handler.
To learn more about event handling with jQuery, I recommend to go through these articles.

相关文章

网友评论

      本文标题:jQuery Ajax 请求的 .done 方法在 chrom

      本文链接:https://www.haomeiwen.com/subject/vicfvxtx.html