weixin_33714884 2014-07-29 04:50 采纳率: 0%
浏览 23

嵌套AJAX和用户事件

I have a mini project where I need to do an ajax call against a relatively slow server, take user input, and then process the ajax response with the user input.

Because it takes a while for the AJAX call to complete, I began the call as soon as the document loaded. In theory, it should be done by the time the user is done with their input.

This is kind of how I have it setup at the moment:

$(document).ready(function() {
    var table = $.ajax({
        . . .
    });

    $('#btn').click(process(table));
};

function process(jqXHR) {
    //code not dependent on AJAX call

    var table = jqXHR.done(function(data) {
        return data;
    });

    //code that is dependent on AJAX call
}

The idea is that I keep the AJAX call asynchronous, but at a certain point I need it to be complete before I can fire off the rest of my code. I thought that jqXHR.done() nested under an onClick() event might be what I'm looking for, but it looks like jqXHR.done() fires regardless of where I put the handler.

So, is there a way to to keep everything running asynchronously up until a certain point, then wait until the AJAX call is finished to continue executing a block of code?

--edit--

I have considered trying to somehow implement callbacks to do it, but honestly I have no idea how to link callbacks from 2 different co-dependent event handlers. The co-dependent nature of it is what is really confusing me.

  • 写回答

2条回答 默认 最新

  • weixin_33725270 2014-07-29 05:24
    关注

    You can use a flag which indicates whether data is loaded or not, if the user clicks on the element and the response is not returned yet, you can inform the user that he/she should wait until an operation is complete.

    // untested
    var jqXHR = $.ajax({
       // . . .
    })
    , isDone = false
    , isClicked = false;
    
    
    $(document).ready(function() {
        $('#btn').click(function() {
           isClicked = true;
           if ( isDone === false ) {
             // show/tell something to the user
           }
           jqXHR.done(function(data) {
              isDone = true;
              if (isClicked) process(data);
           });
        });
    };
    
    function process(data) {
        //code that is dependent on AJAX call
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口