代码一:
代码如下:
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");
};
代码二:
Ajax 同步请求方式:
代码如下:
Synchronize = function(url,param) { function createXhrObject() { var http; var activeX = [ "MSXML2.XMLHTTP.3.0","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",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',false); // ajax同步 对于代码二,为异步的ajax请求,执行结果为:先执行alert(2)再执行alert(1),异步的意思就是说一旦conn.open请求一发出,前端不去等待它的响应便执行后面的代码,所以alert(2)先执行了,然后当响应response到达以后才执行alert(1); 对于代码一,为同步的ajax请求,执行结果为:先执行alert(1)再执行alert(2),同步的意思就是说一旦conn.open请求一发出,前端就去等待它的响应,响应完成以后,alert(1)先执行了,然后alert(2); 原文链接:https://www.f2er.com/ajax/165763.html