如何jQuery的同步AJAX请求工作? [英] How does jQuery's synchronous AJAX request work?

查看:153
本文介绍了如何jQuery的同步AJAX请求工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确实 jQuery.ajax({异步:假})?仍然使用XMLHtt prequest对象

如果是这样,怎么会是要求同步?

时那里只是函数定义,允许由XHR熄异步请求在同步封装包裹?里面的一些机制

我问,因为我想换异步函数调用到同步封装。

修改

我要的依赖做到​​这一点。我需要不运行任何东西,直到所有的外部依赖脚本加载,但是,我宁愿不加载每个文件的同步。

基本上,我想这样的:

 规定(['lib1.js','lib2.js'])Library1Function();
Library2Function();

要加载LIB1和LIB2在同一时间,但直到块都被加载。

我知道我可以用一个回调做到这一点,但是如果我还包括文件包括以同样的方式依赖不起作用。

EDITx2

之所以回调不工作:

 #lib2.js
window.Library2Function =功能(输入){
  警报(输入);
}#lib1.js
需要('lib2.js',函数(){
  window.Library1Function =功能(){
    window.Library2Function('你好');
  }
});#main.js
需要('lib1.js',函数(){
  window.Library1Function();
});

问题是,在main.js,该回调将得到一次被罚下lib1.js被加载并运行。
问题是, Library2Function 实际上并不确定,直到lib2.js被加载,这恰好的之后的lib1.js被解析。


解决方案

  

确实 jQuery.ajax({异步:假})还是用 XMLHtt prequest 对象吗?


XMLHtt prequest。 prototype.open 接受异步作为其第三个参数。如果这是真的(默认值),请求是异步的。否则,它是同步的。


  

我问,因为我想换异步函数调用到同步封装。


你为什么要这么做?这将很可能导致比它修复更多的问题。

Does jQuery.ajax({async: false}) still use the XMLHttpRequest object?

If so, how is the request synchronous?

Is there just some mechanism inside the function definition that allows the asynchronous request put out by the XHR to be wrapped in a synchronous wrapper?

I ask because I want to wrap asynchronous function calls into a synchronous wrapper.

EDIT:

I want to do this for dependencies. I need to not run anything more until all the external dependency scripts are loaded, however, I'd rather not load each of the files synchronously.

Basically, I want this:

require(['lib1.js','lib2.js'])

Library1Function();
Library2Function();

To load lib1 and lib2 at the same time, but block until both are loaded.

I know I could do this with a callback, however that doesn't work if the files I'm including also have dependencies included in the same way.

EDITx2

Reason why callbacks don't work:

# lib2.js
window.Library2Function = function(input) {
  alert(input);
}

# lib1.js
require('lib2.js', function() {
  window.Library1Function = function() {
    window.Library2Function('Hi there');
  }
});

# main.js
require('lib1.js', function() {
  window.Library1Function();
});

The problem is that, in main.js, that callback will get sent off once lib1.js is loaded and run. The problem is, Library2Function isn't actually defined until lib2.js is loaded, which happens after lib1.js is parsed.

解决方案

Does jQuery.ajax({async: false}) still use the XMLHttpRequest object?

Yes.

XMLHttpRequest.prototype.open accepts async as its third parameter. If it's true (default), the request is asynchronous. Otherwise, it's synchronous.

I ask because I want to wrap asynchronous function calls into a synchronous wrapper.

Why do you want to do this? This will most likely result in more problems than it "fixes".

这篇关于如何jQuery的同步AJAX请求工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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