JQuery 之 Ajax 异步和同步浅谈

Ajax 同步和异步的区别

同步是当 JS 代码加载到当前 Ajax 的时候会把页面里所有的代码停止加载,页面出现假死状态;当这个 Ajax 执行完毕后才会继续运行其他代码此时页面假死状态才会解除。反之异步则 Ajax 代码在运行时,其余的 JS 脚本依旧能够运行。


 

在 Jquery 中可以通过 async 的 true 和 false 设置同步或异步,在默认的情况下是为 true 即为异步。

接下来请看下 Sample Code:

$.ajax({ 

        type: "post", 

        url: "path", 

       cache:false, 

       async:false, 

        dataType: "xml"

         success: function(obj){ 

        } 

});

async 这个属性可以相对的减少代码运行顺序问题,但是用的太多的也可能导致页面假死的次数太多,容易降低用户体验。

参考官方给出的解释:

 http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxdataadapter/jquery-data-adapter.htm

async 
Boolean 
Default: true

By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

success 
Function

A function to be called if the request succeeds. The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status. This is an Ajax Event.

这里的话,当 async 默认的设置值为 true ,这种就为异步方式(如果忘记了概念,可参考文章开端简介)

这种执行方式其实执行是有两个线程, 服务端请求一个,后面的 JS 脚本一个。

Sample Code:

$.ajax({  

          type:"POST", 

         url:"xx.aspx=init", 

           dataType:"xml", 

          success:function(data){   //function1()

             f1(); 

             f2(); 

        } 

         failure:function (data) {  

            alert('Failed');  

         }, 

  } 

  function2(); 

在上例中,当ajax块发出请求后,他将停留function1(),等待server端的返回,但同时(在这个等待过程中),前台会去执行function2(),也就是说,在这个时候出现两个线程,我们这里暂且说为function1() 和function2()。

当把asyn设为false时,这时ajax的请求时同步的,也就是说,这个时候ajax块发出请求后,他会等待在function1()这个地方,不会去执行function2(),知道function1()部分执行完毕。

 

转载于:https://www.cnblogs.com/byvar/p/4963020.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值