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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀