jquery $ .post()被取消了 [英] jquery $.post() getting canceled

查看:319
本文介绍了jquery $ .post()被取消了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我执行jquery $ .post()时,我都会收到已取消状态。这似乎是一个异步问题?我使用 http://127.0.0.1:8933/myproject/default/index.html

I'm getting a "canceled" status whenever I do a jquery $.post(). It seems like an asynchronous problem? I access the local project with http://127.0.0.1:8933/myproject/default/index.html

index.html:

index.html:

<script>
    $(document).ready(function() {
         $('#mybutton').click(function() {
                var post_url = get_url();  // resolves to "/myproject/default/process_func"
                var data = ...;
                do_action(post_url, data); 
         });
    });
</script>

<a href="" id="mybutton"> Click me! </a>

util.js:

function doPost(url, data) {
    $.post(url, data).then(doSuccess, doFail):

    function doSuccess(data) {
           alert('Successful!');
    }
    function doFail(data) {
           alert('Failed!');
    }
}

function do_action(url, data) {
    var jsondata = JSON.stringify(data);
    // some other stuffs...

    doPost(url, jsondata);
}

我们的想法是将一些数据发回服务器,以便使用json数据进行处理。用户将点击锚点按钮, do_action()将触发,然后它将被发布在 doPost()

The idea is to post some data back to the server for processing using json data. A user will click on the anchor button, the do_action() will fire, and then it'll be posted in doPost().

这似乎有效,因为我看到json数据传递给服务器上的处理函数。但是,我会看到警告消息失败!即使数据已被处理,每次都会弹出。在chrome的调试面板中,我在网络选项卡下看到帖子状态为(已取消),整条线将以红色突出显示。声明的Type是待定。

This seems to work since my I'm seeing the json data passed to my processing function on the server. However, I'd see the alert message "Failed!" pop up every time even though the data has been processed. In chromium's debug panel, I see under "Network" tab that the post has a status of "(canceled)" and the entire line would be highlighted in red. The Type stated is "Pending".

我认为这是一个异步问题,但我不确定如何修复它。

I think this is an asynchronous problem, but I'm unsure how to fix it.

推荐答案

使用此方法取消< a> 的默认导航行为:

Use this, to cancel the default navigatin behavior of the <a>:

$('#mybutton').click(function(e) {  // <-- Add `e` here
    e.preventDefault();  // <-- Add this line
    var post_url = get_url();
    var data = ...;
    do_action(post_url, data); 
});

我相信浏览器会中止AJAX请求,因为点击链接时,请求确实发送后,链接尝试导航到新页面,以便浏览器必须中止打开的AJAX请求。

I believe the AJAX request is being aborted by the browser because when clicking the link, although the request does get sent off, the link tries to navigate to a new page so the browser must abort open AJAX requests.

这篇关于jquery $ .post()被取消了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆