您的位置:首页 > Web前端 > JQuery

JQuery 之 Ajax 异步和同步浅谈

2015-11-13 18:24 661 查看
[b]Ajax 同步和异步的区别[/b]

同步是当 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()部分执行完毕。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: