如何在运行时取消ajax请求并清除信息?

时间:2014-10-16 04:35:00

标签: javascript jquery ajax click

这是我所拥有的代码片段。默认情况下,“ajax_info_box”被隐藏,通过单击“按钮”,“ajax_info_box”显示并发送请求,结果可能需要大约5秒钟。如何通过单击“取消”取消并清除请求?任何帮助将不胜感激。

   $('.ajax_info_box').hide()
   $('.button').click(function() {
   $('.ajax_info_box').show()
    var xhr =  $.ajax({
        type: "POST",
        url: 
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
          do something here

    });
    $('.cancel').click(function () {
       suppose to kill the request here
       $('.ajax_info_box').hide()
    }); 
});

2 个答案:

答案 0 :(得分:2)

xhr上有一个中止方法

xhr.abort()

更多Abort Ajax requests using jQuery

答案 1 :(得分:0)

   $('.ajax_info_box').hide()
   $('.button').click(function() {
   $('.ajax_info_box').show()
    var xhr =  $.ajax({
        type: "POST",
        url: 
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
          do something here

    });
    $('.cancel').click(function () {
       xhr.abort();
       $('.ajax_info_box').hide()
    }); 
});