如何使用纯Javascript实现同步Ajax调用
How can implement synchronous Ajax call using pure Javascript?
我需要实现同步Ajax调用机制。我已经实现了ajax调用函数在我的助手相同如下:
MH.helper = {
ajax : function (option) {
if(option !== undefined) {
for(var opt in option) {
this[opt] = option[opt];
}
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
this.xhr=new XMLHttpRequest();
} else {
// code for IE6, IE5
this.xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
}
}
我还实现了Ajax原型如下:
MH.helper.ajax.prototype = {
// XMLHttpRequest obj
xhr : null,
// request url
url: '',
// post funciton
post: function() {
var xhr = this.xhr;
var that = this;
xhr.onreadystatechange=function() {
if(xhr.readyState==4 && xhr.status==200){
if(that.complete && ( typeof that.complete === 'function' )) {
that.complete(xhr.responseText);
}
}
}
var data = MH.helper.serialize(this.data, true);
xhr.open("POST",this.url,true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
},
// get funciton
get: function() {
var xhr = this.xhr;
var that = this;
xhr.onreadystatechange=function() {
if(xhr.readyState==4 && xhr.status==200){
if(that.complete && ( typeof that.complete === 'function' )) {
that.complete(xhr.responseText);
}
}
}
var data = MH.helper.serialize(this.data);
xhr.open("GET",this.url+data,true);
xhr.send(data);
},
// callback when request done
complete: null
}
任何人都有任何想法,我如何实现同步调用使用我的Ajax函数?
xhr.open("POST",this.url,true)
如果你传递false
作为第三个参数,而不是true
,调用将同步执行。
但我的建议-不要。始终使用回调函数
传递false
作为xhr.open
的第三个参数
来源:规范,MDN文章
相关文章:
- 如何模拟同步ajax调用?(基于异步的同步)
- 使用同步ajax调用加载屏幕
- 同步 Ajax 请求将导致页面上出现任何问题
- 同步AJAX(失信)
- 使用jsonp解决方法进行同步ajax调用
- 使用jQuery同步Ajax请求;我不能在Adobe Air上工作
- 通过递归循环同步ajax请求
- 将同步 AJAX 逻辑替换为异步逻辑
- window.onbeforeunload,关闭浏览器和同步AJAX
- 有没有办法同步 ajax 调用
- 没有同步 ajax 的弹出窗口
- 如何将同步 ajax 调用替换为凭据以保持应用状态稳定
- ASP.NET 对同步 AJAX 请求的 MVC 操作
- 如何使用同步 ajax 请求将音频转换为 arrayBuffer
- Web 视图中的同步 Ajax 超时
- JavaScript同步Ajax请求习语
- 同步Ajax请求”;锁定“;浏览器
- 使用JSONP同步AJAX请求
- 无阻塞同步AJAX
- Chrome中同步AJAX调用冻结前的代码