ajax -async 参数同步异步

本文探讨了在使用Ajax请求时如何通过设置同步请求来获取返回值并将其赋值给全局变量的方法。介绍了同步请求的实现方式及其限制,如不支持跨域请求和数据类型为'jsonp'的请求,并提醒开发者注意同步请求可能导致的浏览器锁定问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发项目写功能的时候,需要将ajax的返回值赋到全局变量中,然后在该页面其他地方引用,因为ajax异步的原因一直无法成功,只需将async:false,就OK了。

 

写这个帖子的原因是因为。。。每次需要同步的时候,我记不住‘asyns'这个单词的拼写,每次都得去其他的js里面粘一边过来,为了加深记忆,决定写个使后感。。。

 

  • async (default:  true)
    Type:  Boolean
    By default, all requests are sent asynchronously (i.e. this is set to  true by default). If you need synchronous requests, set this option to  false. Cross-domain requests and  dataType: "jsonp"requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.  As of jQuery 1.8, the use ofasync: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

 

以上为jquery官网给出的API。

 
By default, all requests are sent asynchronously

 ajax默认所有请求都是设置为异步的

 
If you need synchronous requests, set this option to false

 如果需要同步,则设为false

写道
Cross-domain requests and dataType: "jsonp"requests do not support synchronous operation.

 

同步不支持跨域请求和数据类型:’jsonp'请求

 

什么是jsonp,json和jsonp的区别,请戳这里

 

 
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

 

请注意,同步请求可能会暂时锁定浏览器,停止任何行为,直到该请求完成

 
As of jQuery 1.8, the use ofasync: false with jqXHR ($.Deferred) is deprecated;

 在jquery1.8中,如果将请求设置为同步的话,则不支持延迟方法($.Deferred详细内容戳这里,讲的挺好的)

开发网站的过程中,我们经常遇到某些耗时很长的javascript操作。其中,既有异步的操作(比如ajax读取服务器数据),也有同步的操作(比如遍历一个大型数组),它们都不是立即能得到结果的。
通常的做法是,为它们指定回调函数(callback)。即事先规定,一旦它们运行结束,应该调用哪些函数。
简单说,deferred对象就是jQuery的回调函数解决方案。在英语中,defer的意思是"延迟",所以deferred对象的含义就是"延迟"到未来某个点再执行。

 

 

you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

 所以你必须使用成功/失败/完成的回调函数来替代延迟方法或者不使用延迟方法

 

 

 

 

总结一下:

1.如果请求是异步的,不能在回调之外直接拿到返回的data

2.如果设为同步的话,会阻塞后面的代码,也就是说如果这个请求需要执行30秒,就必须等30秒执行完之后,才能继续执行下面的

3.同步不支持跨域请求和数据类型:’jsonp'请求

4,如果将请求设置为同步的话,则不支持延迟方法,不能使用$.Deferred,只能使用success/error/complete

来代替比如 deferred.always()/$.when 等

 

。。。虽然写完了,但是还是不大记得asyns怎么拼啊。。看来要去背背“asynchronous”这个发音了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值