ajax同步请求和异步请求的差异
ajax同步和异步的差异, 先看2段代码:
代码一:
Synchronize = function(url,param) {
function createXhrObject() {
var http;
var activeX = [ "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
try {
http = new XMLHttpRequest;
} catch (e) {
for (var i = 0; i < activeX.length; ++i) {
try {
http = new ActiveXObject(activeX[i]);
break;
} catch (e) {}
}
} finally {
return http;
}
}
var conn = createXhrObject();
conn.open("POST", url, false);//ajax同步
conn.send(param);
var strReturn = conn.responseText;
alert("1");
if (strReturn != "") {
return Ext.decode(conn.responseText);
} else {
return null;
}
alert("2");
};
function createXhrObject() {
var http;
var activeX = [ "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
try {
http = new XMLHttpRequest;
} catch (e) {
for (var i = 0; i < activeX.length; ++i) {
try {
http = new ActiveXObject(activeX[i]);
break;
} catch (e) {}
}
} finally {
return http;
}
}
var conn = createXhrObject();
conn.open("POST", url, false);//ajax同步
conn.send(param);
var strReturn = conn.responseText;
alert("1");
if (strReturn != "") {
return Ext.decode(conn.responseText);
} else {
return null;
}
alert("2");
};
代码二:
Ajax 同步请求方式:
Synchronize = function(url,param) {
function createXhrObject() {
var http;
var activeX = [ "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
try {
http = new XMLHttpRequest;
} catch (e) {
for (var i = 0; i < activeX.length; ++i) {
try {
http = new ActiveXObject(activeX[i]);
break;
} catch (e) {}
}
} finally {
return http;
}
}
var conn = createXhrObject();
conn.open("POST", url, true);//ajax异步
conn.send(param);
var strReturn = conn.responseText;
alert("1");
if (strReturn != "") {
return Ext.decode(conn.responseText);
} else {
return null;
}
alert("2");
};
Synchronize = function(url,param) {
function createXhrObject() {
var http;
var activeX = [ "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
try {
http = new XMLHttpRequest;
} catch (e) {
for (var i = 0; i < activeX.length; ++i) {
try {
http = new ActiveXObject(activeX[i]);
break;
} catch (e) {}
}
} finally {
return http;
}
}
var conn = createXhrObject();
conn.open("POST", url, true);//ajax异步
conn.send(param);
var strReturn = conn.responseText;
alert("1");
if (strReturn != "") {
return Ext.decode(conn.responseText);
} else {
return null;
}
alert("2");
};
同步和异步的差异如下:
conn.open('POST',Url,true); // ajax异步
conn.open('POST',Url,false); // ajax同步
url:http://greatverve.cnblogs.com/archive/2011/07/02/ajax-js.html
对于代码二,为异步的ajax请求,执行结果为:先执行alert(2)再执行alert(1), 异步的意思就是说一旦conn.open请求一发出,前端不去等待它的响应便执行后面的代码,所以alert(2)先执行了,然后当响应response到达以后才执行alert(1);
对于代码一,为同步的ajax请求,执行结果为:先执行alert(1)再执行alert(2), 同步的意思就是说一旦conn.open请求一发出,前端就去等待它的响应,响应完成以后,alert(1)先执行了,然后alert(2);
我这个博客废弃不用了,今天想寻找外链的时候,突然想到这个博客权重很高。
有需要免费外链的,留言即可,我准备把这个博客变成免费的友情链接站点。