如何使用纯Javascript实现同步Ajax调用

How can implement synchronous Ajax call using pure Javascript?

本文关键字:同步 Ajax 调用 实现 Javascript 何使用      更新时间:2023-09-26

我需要实现同步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文章