在同一时间执行同步和异步AJAX [英] Performing Synchronous AND Asynchronous AJAX at the Same Time

查看:153
本文介绍了在同一时间执行同步和异步AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行AJAX来得到一些URL数据,构建数据对象并将其分配给一个全局对象变量。所以我知道我需要运行的同步的Ajax请求。 (对吗?)嗯,我也想利用在 beforeSend 设置给我的用户一个载入画面。 (我也许应该问第一个,是beforeSend只有这样,才能做到这一点?)怎么会结合我的好处同步和异步?

I'm wanting to run AJAX to get some URL data, build an object from the data and assign it to a global object variable. So I know I need to run a synchronous ajax request. (Right?) Well I also want to make use of the beforeSend setting to give my users a loading screen. (I probably should be asking first, is beforeSend the only way to achieve that?) How might I combine the benefits sync and async?

异步:

$.ajax({
        url:'scripts/scripts.php?call=page&url='+thisurl, /*local*/
        dataType:'html',
        beforeSend:function(){
            $('#display').html('<div class="loading"></div>');
        },
        success:function(data, textStatus, jqXHR){
            /*local*/ myobj = getMyObj(data); $('#display').html(myobj);
        },
        error:function(jqXHR, textStatus, errorThrown){ }
});

同步:

$.ajax({
        url:'scripts/scripts.php?call=page&url='+thisurl, /*local*/
        dataType:'html',
        async:false,
        success:function(data, textStatus, jqXHR){
            /*global*/ myobj = getMyObj(data);
        }
});
$('#display').html(myobj);

抱歉,如果这是没有意义的。

sorry if this doesn't make sense

推荐答案

埃姆,好了,这是pretty的明显,如果你想显示同步AJAX功能,在此之前的东西:

Ehm, well, it's pretty obvious that if you want to display something before a synchronous ajax function you do:

$('#display').html('<div class="loading"></div>');
$.ajax({
        url:'scripts/scripts.php?call=page&url='+thisurl, /*local*/
        dataType:'html',
        async:false,
        success:function(data, textStatus, jqXHR){
            /*global*/ myobj = getMyObj(data);
        }
});
$('#display').html(myobj);

在另一方面,为什么使用同步的Ajax功能,这是一个非常糟糕的主意,用承诺来替代,或者是这样的:

On the other hand why use a synchronous Ajax function, it's a really bad idea, use promises instead, or something like:

var Ajax = $.ajax({
              url:'scripts/scripts.php?call=page&url='+thisurl,
              dataType:'html'
           });

//do something later
$("#mybutton").on('click', function() {
    Ajax.done(function(data) {         //if/when the ajax function is completed
        $('#display').html(data);
    });
});        

还是坚持了ajax在一个单独的功能和运行方式相同,也有很多选择比同步的Ajax调用等!

Or stick the ajax in a seperate function and run that the same way, there are many options other than synchronous Ajax calls!

这篇关于在同一时间执行同步和异步AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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