Get response from server using Javascript after Javascript request

My Javascript function request to aspx page. The code:

 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 from this page and catch it on the client side. How to do it?

+3
source share
3 answers

To get a response from XMLHttpRequestin asynchronous mode (the third parameter truefor the method open()), you must set the property onreadystatechangein the callback function. This function will be called when the response is ready in the browser:

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 can read the following article for further reading on the topic:

+6
source

, 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();

:

("XMLHttpRequest" in window)

in, , , , , .

, IE7 +, native nativeHttpHttpRequest , XMLHttpRequest window, null. , ActiveX () , :

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

, -, - . p >

// making a call is as simple as this
ajax( "http://www.example.net/abc.aspx", function( data ){
    // do something with the server 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;
}​
+2

Source: https://habr.com/ru/post/1753502/


All Articles