码迷,mamicode.com
首页 > Web开发 > 详细

ajax同步与异步的实践

时间:2015-06-21 22:16:53      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:

写在前面:本文中所有测试实例皆基于mac版chrome, firefox及safari。

同步请求

同步请求,其实也就是告诉js引擎:你先把我这个处理了再做别的事情!所以同步无需等,在send()之后直接往responseText中拿数据就好。

  1. function req() {
  2. var xhr = new XMLHttpRequest();
  3. xhr.open(‘get‘, ‘./data.json‘,false);
  4. xhr.send();
  5. console.log(xhr.responseText);
  6. }
  7. req();

注:在同步请求时,各浏览器都会提示同步方法已不建议使用,因为它会影响主线程。原话是:Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user‘s experience. For more help, check http://xhr.spec.whatwg.org/.

异步请求

异步请求就是自身(XMLHttpRequest对象)绑定个事件先,告诉js引擎说:我这儿有个请求哈,老兄有空帮我处理下,完了帮我把回调也处理下。

  1. function req() {
  2. var xhr = new XMLHttpRequest();
  3. xhr.onreadystatechange = function (e) {
  4. if (xhr.readyState == 4 && xhr.status == 200) {
  5. console.log(xhr.responseText);
  6. }
  7. }
  8. xhr.open(‘get‘, ‘./data.json‘);
  9. xhr.send();
  10. }

同步用回调会咋办?!

前段时间因为XMLHttpRequest对象找到MDN看,其中里面有提示开发者,如果用了同步请求,那么不要用onreadystatechange做绑定了,这很明白,你都同步了,就无需再绑定了嘛。我误操作(手贱),额....

  1. function req() {
  2. var xhr = new XMLHttpRequest();
  3. xhr.onreadystatechange = function (e) {
  4. //console.log(xhr.readyState);
  5. if (xhr.readyState == 4 && xhr.status == 200) {
  6. console.log(xhr.responseText);
  7. }
  8. }
  9. xhr.open(‘get‘, ‘./data.json‘,false);
  10. xhr.send();
  11. console.log(xhr.responseText);
  12. }

结果还真输出来了结果....这是个什么情况?引擎依然没有忘记去查下回调。。。
去掉line4的注释,发现有两个状态被打印出来,分别是1(send()方法还未被调用)和4(请求结束).
去掉line11的注释,证实其执行顺序为请求-回调-同步操作(即这里的line11).

既然执行了回调,为什么状态却只有1和4?

查看MDN时有这么一句话: If the request is asynchronous (which is the default), this method returns as soon as the request is sent. If the request is synchronous, this method doesn‘t return until the response has arrived.
也就是说,send调用后,如果请求是异步的,它会在调用后马上返回;如果请求是同步的,那么它会等到请求完成后再返回。这也就解释了上面的同步请求中为什么只有1和4两个状态了。
啰嗦了这么多,纯属没事瞎bb,一句话,尽量少用同步,用同步别用事件绑定。

再试试在子进程中执行同步请求:

原脚本改为:

  1. var w=new Worker(‘./worker.js‘);
  2. w.onmessage=function(e){
  3. console.log(e.data);
  4. }

新建脚本文件worker.js

  1. function req() {
  2. var xhr = new XMLHttpRequest();
  3. xhr.open(‘get‘, ‘./data.json‘,false);
  4. xhr.send();
  5. postMessage(xhr.responseText);
  6. }
  7. req();

此时浏览器便不再提示上面说的Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user‘s experience. For more help, check http://xhr.spec.whatwg.org/.了。





ajax同步与异步的实践

标签:

原文地址:http://www.cnblogs.com/rubyisaPM/p/4592492.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!