简体   繁体   English

在javascript中同步运行ajax请求?

[英]Running ajax request in javascript synchronously?

I am having this problem with my code. 我的代码有这个问题。 I have a function performing AJAX call and bringing up the interface and that AJAX is separated in a different function. 我有一个执行AJAX调用并调出接口的函数,并且AJAX被分离在另一个函数中。 I am calling it in somewhere and some code follows it. 我在某个地方调用它,并跟随一些代码。 Here is an example : 这是一个例子:

function doAjaxStuff(){
//do something
}

function anotherFunction(){
doAjaxStuff();
//proceed with further code
}

(The function anotherFunction is getting called from $(document).ready ) (从$(document).ready调用函数anotherFunction

As the further code is completely dependent upon the things I'm loading, like I'm trying to accessing an element and it hasn't loaded yet which gives me null value and nothing works. 由于进一步的代码完全取决于我要加载的内容,例如我正在尝试访问一个元素,但尚未加载,这给了我null值,并且没有任何效果。 So if i could just wait till the function that i called in anotherFunction gets executed completely then it would be easier for me to deal with it. 因此,如果我可以等到我在anotherFunction调用的函数完全执行后,对我来说将更容易处理。 I've seen promises if I'm not wrong helps in making code synchronous (Not able to understand how to implement that). 我看过没有错误的promises有助于使代码同步(无法理解如何实现)。 Help me out! 帮帮我!

You can pass a callback function as argument to doAjaxStuff and call it when your ajax request is done. 您可以将回调函数作为参数传递给doAjaxStuff ,并在ajax请求完成时调用它。

function doAjaxStuff(callback) {
    $.ajax({
        success: function(data) {
            // do some stuff with data
            callback(data);
        }
    });
}

function anotherFunction() {
    doAjaxStuff(function(data) {
        alert(data);
    })
}

In JavaScript, functions are also objects, which means they can be passed as argument to another function as well as you can do with any other value. 在JavaScript中,函数也是对象,这意味着它们可以作为参数传递给另一个函数,也可以使用任何其他值来传递。 So in this case we have a parameter called callback in the function doAjaxStuff . 因此,在这种情况下,我们在doAjaxStuff函数中有一个名为callback的参数。 When the ajax request is complete, we can call this function that was passed as argument. 当ajax请求完成时,我们可以调用此作为参数传递的函数。

Another way is to use deferred objects 另一种方法是使用deferred对象

function doAjaxStuff(){
  return $.ajax(...);
}


function anotherFunction() {
    $.when(doAjaxStuff()).then(function(){
       // other code to run after ajax call
    });
}

try something like this 尝试这样的事情

      $.ajax({
        url:"demo_test.txt",
        async:false,
        success:function(result){
        }
     });

all requests are sent asynchronously (ie this is set to true by default). 所有请求都是异步发送的(即默认情况下设置为true)。 If you need synchronous requests, set this option to false 如果需要同步请求,请将此选项设置为false

REFERENCE 参考

http://api.jquery.com/jquery.ajax/ http://api.jquery.com/jquery.ajax/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM