如何使它与Asynchronous一起使用

时间:2014-05-18 02:19:49

标签: javascript ajax asynchronous

我希望能够使用Asynchronous方法获得结果。有些原因只适用于其他方法。我试图返回回调方法的响应。 所以我可以做到

ajax.getResults(); 

而不是:

ajax.getResults(function(response){
    // code here...
});

这是代码......

function Ajax(method, destination, sendType){
    this.method=method;
    this.destination=destination;
    this.sendType=sendType;
    // creates xmlhttp object
    this.create=function(){
        var xmlhttp;
        if(window.XMLHttpRequest){
            xmlhttp=new XMLHttpRequest();
        }else{
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlhttp;
    }
    this.request=function(callback){
        var xmlhttp=this.create();
        xmlhttp.onreadystatechange=function(){
            if(xmlhttp.readyState==4 && xmlhttp.status==200){
                // response
                callback(xmlhttp.responseText);
            }
        }
        xmlhttp.open(this.method, this.destination, this.sendType);
        xmlhttp.send();
    }
}

// trying to get results from this.request()
Ajax.prototype.getResults=function(){
    var result;
    this.request(function(response){
        result=response;
    });
    return result;
}

function ajaxTest(){
    var ajax=new Ajax('POST', 'echo.php', true);
    alert(ajax.getResults());
}

0 个答案:

没有答案