在 Javascript 请求后使用 Javascript 从服务器获取响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3193976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:37:56  来源:igfitidea点击:

Get response from server with Javascript after Javascript request

javascriptrequestresponse

提问by Murat

My Javascript function request to a aspx page. ?ts Code:

我对 aspx 页面的 Javascript 函数请求。?ts 代码:

 var xhr = ("XMLHttpRequest" in window) ? new XMLHttpRequest() : new ActiveXObject("Msxml3.XMLHTTP");
    xhr.open("GET", = 'http://www.example.net/abc.aspx', true);
    xhr.send(""); 

After this request I want to send a response back from this page and catch it on the client side. How do I do that?

在此请求之后,我想从此页面发回响应并在客户端捕获它。我怎么做?

回答by Daniel Vassallo

To get the response from XMLHttpRequestin asynchronous mode (third parameter is truefor the open()method) you have to set the onreadystatechangeproperty to a callback function. This function will be called back when the response is ready at the browser:

XMLHttpRequest以异步模式(第三个参数true用于open()方法)获取响应,您必须将该onreadystatechange属性设置为回调函数。当浏览器准备好响应时,将回调此函数:

xhr.open("GET", 'http://www.example.net/abc.aspx', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4)  { 
    var serverResponse = xhr.responseText;
  }
};
xhr.send(null);

You may want to check out the following article for further reading on the topic:

您可能需要查看以下文章以进一步阅读该主题:

回答by bobince

To get the response, add a readystatechangeevent handler function. This will get called back when the response is ready to read:

要获得响应,请添加readystatechange事件处理函数。当响应准备好读取时,这将被回调:

xhr.onreadystatechange= function() {
    if (this.readyState!==4) return; // not ready yet
    if (this.status===200) { // HTTP 200 OK
        alert(this.responseText);
    } else {
        // server returned an error. Do something with it or ignore it
    }
};
xhr.open('GET', 'http://www.example.net/abc.aspx', true);
xhr.send();

Incidentally:

顺便:

("XMLHttpRequest" in window)

Whilst inis in general a good way to test whether a property exists, this is one of the very few places where it's not ideal.

虽然in通常是测试属性是否存在的好方法,但这是极少数不理想的地方之一。

The problem is that in IE7+, when the ‘native XMLHttpRequest' option is turned off, XMLHttpRequeststill exists as a property in window, but with the unusable value null. So it's better in this specific case to use a simple truth test, which will allow fallback to ActiveX in the (unlikely) event that this option is disabled:

问题在于,在 IE7+ 中,当“native XMLHttpRequest”选项关闭时,XMLHttpRequest仍然作为 中的属性存在window,但值不可用null。因此,在这种特定情况下最好使用简单的真值测试,这将允许在禁用此选项的(不太可能)事件中回退到 ActiveX:

var xhr= window.XMLHttpRequest? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHttp');

回答by gblazex

You have to do a little moreto get it work cross-browser, but once it's done you've got a reusable function, without any library.

您必须做更多的工作才能使其跨浏览器工作,但是一旦完成,您就拥有了一个可重用的函数,而无需任何库。

// making a call is as simple as this
ajax( "http://www.example.net/abc.aspx", function( data ){
    // do something with the server's response
    alert(data);
});

///////////////////////////////////////////////////////////////////////////////

function getXmlHttpObject() {
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if (!xmlHttp) {
        alert("Your browser does not support AJAX!");
    }
    return xmlHttp;
}


function ajax(url, onSuccess, onError) {

    var xmlHttp = getXmlHttpObject();

    xmlHttp.onreadystatechange = function() {
      if (this.readyState === 4) {

            // onSuccess
            if (this.status === 200 && typeof onSuccess == 'function') {
                onSuccess(this.responseText);
            }

            // onError
            else if(typeof onError == 'function') {
                onError();
            }

        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    return xmlHttp;
}?