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

6

我的JavaScript函数请求一个aspx页面。

它的代码:

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

在此请求之后,我想从此页面发送响应并在客户端上捕获它。我该如何做到这一点?

Murat,你应该看一下JavaScript框架(比如jQuery)来完成这个任务。它是跨浏览器的,而且相当简单明了。 - Kris Krause
4个回答

7

为了以异步模式(open()方法的第三个参数为true)从XMLHttpRequest获取响应,您需要将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);

您可能想进一步阅读以下文章来了解有关该主题的更多信息:


谢谢大家。所有的答案都解决了我的问题。 - Murat

3
为了获得响应,请添加一个 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+中,当“本机XMLHttpRequest”选项关闭时,XMLHttpRequest仍然作为window中的属性存在,但其值为无法使用的null。因此,在这种特定情况下最好使用简单的真实测试,这将允许在(不太可能的)情况下回退到ActiveX:

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

3

要使它在各种浏览器上正常运行,您需要 额外努力一些,但完成后,您将拥有一个可重用的函数,而无需任何库。

// 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;
}​

0
如果你喜欢使用jQuery来进行ajax调用,可以使用以下代码:
  const data = { info1: "Data", info2: "Data"};

  const reqUrl = "http://www.example.net/abc.aspx";

  $.ajax({
    type: "POST",
    url: reqUrl,
    data: data,
  })
    .done(function (data, status, jqXHR) {
      // Do your stuff
    })
    .fail(function (data, status, jqXHR) {
      alert("Sorry, can't currently reach Server :(");
    })
    .always(function (data, status, jqXHR) {});

你的回答可以通过提供更多支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人能够确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接