How can implement synchronous Ajax call using pure Javascript?

我的未来我决定 提交于 2020-12-15 03:39:45

问题


I need to implement synchronous Ajax calling mechanism. I already implement ajax calling function in my helper same as below :

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");
        }
    }
}

I also implement Ajax prototype as same as below :

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
}

Anyone have any idea how can I implement synchronous call using my Ajax function?


回答1:


Pass false as the third argument of xhr.open.

Sources: Specification, MDN article.




回答2:


xhr.open("POST",this.url,true)

If you pass false as the 3rd parameter instead of true - the call will be performed synchronously.

But my advice - don't. Use callback functions always.



来源:https://stackoverflow.com/questions/22463579/how-can-implement-synchronous-ajax-call-using-pure-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!