简体   繁体   中英

Javascript DoEvents equivalent?

Here is my shortened code snippet:

$(document).ready(function() {
$.get("/Handlers/SearchData.ashx",
function(data) {
json = $.evalJSON(data);
});

//do some other stuff

//use json data

alert(json == null);

});

Alert says true because evalJson is not done processing JSON data yet (21kb gzipped). I need to wait somehow for it to finish before using that data - exactly what I'd do with DoEvents in a while loop.

Instead of executing evalJSON yourself, why not let jQuery figure out when it's done:

$.ajax({
  url:"/Handlers/SearchData.ashx",
  type: "get",
  dataType: "json",
  success:function(d) {
    //d now contains a JSON object, not a string.
    alert(d==null);
  }
});

There is no equivalent to DoEvents, but you can put the code that depends on your JSON data into a function and call it from the AJAX callback. You can also use the $.getJSON method so you don't have to eval the JSON yourself.

$(document).ready(function() {
    $.getJSON("/Handlers/SearchData.ashx",
    function(data) {
        json = data;
        stuffToDoAfterIHaveData();
    });

    //do some other stuff
});

//use json data
function stuffToDoAfterIHaveData() {
    alert(json == null);
}

Alternatively, jQuery offers a way to make AJAX requests synchronous (ie they halt code execution until the response comes back). You can use $.ajaxSetup({ async: false }); or you can call the $.ajax method directly and pass async:false in the options object.

You can use like this:

$(document).ready(function(){
    json = $.parseJSON(
        $.ajax({url: '/Handlers/SearchData.ashx', async: false}).responseText
    )

    alert(json == null);
})

The only thing similar to doEvents in javascript is setTimeout(). the First argument should be a string with the Code you want to execute after the "system events" are done, and the second argument is the number of milisecs to wait... It's complicated but that is the only solution I know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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