jQuery的$就去年成功发射去年、jQuery

由网友(不负勇往)分享简介:我有以下的Javascript和它的返回结果出来的订单我希望他们。I have the following Javascript and it's returning results out of the order I would expect them.function getCurrentItems(id){...

我有以下的Javascript和它的返回结果出来的订单我希望他们。

I have the following Javascript and it's returning results out of the order I would expect them.

function getCurrentItems(id){
    alert("2");
    $.ajax({
        url: "somePHPurlthatspitsoutajsonencodedArray.php",
        type: "POST",
        dataType: "json'",
        data: {id:id},
        success: function(data){
            alert("3");
        }
    });
    alert("4");
}

$(document).on('click', '.eventClass', function(e){
    alert("1");
    var id = "someID";
    var results = getCurrentItems(id);
    alert("5");
});

我想我会得到警报,1的顺序2,3,4,5。

I would think I'd get alerts in the order of 1, 2, 3, 4, 5.

而我得到他们的顺序1,2,4,5,3。

Instead I get them in the order of 1, 2, 4, 5, 3.

我只是不明白,为什么是成功的警报(5)触发最后?

I just can't figure out why that success alert (5) fires last?

推荐答案

AJAX是短期的异步JavaScript和XML。异步是这里的关键词。我会用一个比喻来解释异步。

AJAX is short for asynchronous JavaScript and XML. Asynchronous is the keyword here. I'll use an allegory to explain async.

假设你正在手工洗碗。你不能做任何事情,而这样做,所以它是同步的。

Lets say you're washing dishes manually. You can't do anything else while doing that, so it is synchronous.

比方说,你把你的菜在洗碗机。你可以做其他的事情,你已经委派任务,洗碗机,所以这是异步的。异步一般是越多越好,因为你可以在同一时间做多件事情。 Javascript的唯一asyncs从服务器请求的信息,因为JavaScript是单线程(它只能运行在1个CPU内核,只能做一件事的时间在它自己的)的时候。

Lets say you put your dishes in a dishwasher. You can do other things, you've delegated the task to the dishwasher, so this is asynchronous. Asynchronous is generally better, because you can do multiple things at one time. Javascript only asyncs when requesting info from the server, as Javascript is single threaded (it only runs on 1 CPU core and can only do one thing at a time on it's own).

一个回调是一个异步任务完成时调用的函数。洗碗机完成,所以现在必须要尽快清空你完成你在做什么,当它finshed。

A callback is a function that is called when the async task completes. The dishwasher finishes, so now you have to empty it as soon as you complete what you're doing when it finshed.

因此​​,在您code,你开始洗碗,说你要提醒(3)时,洗碗机结束运行,然后你去警告4和5。然后,当洗碗机完成/你的服务器返回的数据,提醒您3就像你说你会的。

So in your code, you start the dishwasher, say you're going to alert("3") when the dishwasher finishes running, and then you go alert 4 and 5. Then when the dishwasher finishes/your server returns data, you alert 3 like you said you would.

这有意义吗?

阅读全文

相关推荐

最新文章