JQuery的AJAX请求同步行为由于未知原因 [英] JQuery AJAX request behaving synchronous for unknown reason

查看:149
本文介绍了JQuery的AJAX请求同步行为由于未知原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我要被异步运行以下code,但日志显示他们正在同步运行。

I have the following code which I want to be running asynchronously, but the logs are showing that they are running synchronously.

$(".widget").each(function() {
    // snip - url, def, and tempParams defined here
$.ajax({
    url: url, 
    dataType: "jsonp", 
    type: "POST",
    data: {params: tempParams},
    success: function(data) {
        var st = new Date().getTime();
        console.error("Start " + def.name + " @" + st);
        doSomething(data);
        var et = new Date().getTime();
        console.error("End " + def.name + " @" + et);
        console.error("Duration " + def.name + " " + (et-st) + " ms.");
    }
});

控制台输出清楚地表明执行的顺序,而不是异步成功的功能:

The console output clearly shows the success functions executing in order, rather than asynchronously:

Start f1 @1300738891705
End f1 @1300738891744
Duration f1 39 ms.
Start f2 @1300738892746
End f2 @1300738893280
Duration f2 534 ms.
Start f3 @1300738893282
End f3 @1300738893303
Duration f3 21 ms.
Start f4 @1300738893305
End f4 @1300738893306
Duration f4 1 ms.
Start f5 @1300738893484
End f5 @1300738895609
Duration f5 2125 ms.

思考?我觉得这一定有什么明显的是我俯瞰。

Thoughts? I feel like this must be something obvious that I'm overlooking.

推荐答案

我想你们都混淆了两届。异步在AJAX方面并因此JQuery的只是意味着在HTTP请求消息将被发送到Web服务器,而不会导致在客户端的端的任何延迟。该请求将很可能后期到服务器的顺序,但我不认为这是保证。我想你想的线程方面...

I think you're both confusing the two terms. Asynchronous in terms of AJAX and thus JQuery just means that the HTTP Request message will be sent to the webserver without causing any delay on the client's end. The requests will more than likely post to the server sequentially, but I don't think it's guaranteed. I think you're thinking in terms of threading...

同步调用可能会导致延迟在客户端,而浏览器的JavaScript跨preTER等待Ajax响应。

Synchronous calls may cause delay on the client side while the browser's javascript interpreter is waiting for the AJAX response.

要想到一个简单的例子中,假设你有一个AJAX调用获取给定的一个美国州税率。如果这是一个同步调用,那么结账工具将停止计算,并与Javascript的任何用户交互不会产生响应,直到Ajax响应(与税率)接收。

To think of a quick example, lets say you have an AJAX call that fetches the tax rate given a USA state. If it was a synchronous call, then the checkout tool would stop calculation, and any user interaction with Javascript would not produce a response until the AJAX response (with the tax rate) was received.

在上面异步的情况下,你可以定义一个回调函数将继续计算出最终结算价一度收到Ajax响应。

In an asynchronous situation from above, you could define a callback function that would continue to calculate the final checkout price once the AJAX response was received.

这篇关于JQuery的AJAX请求同步行为由于未知原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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