【问题标题】:How to get the response of XMLHttpRequest?如何获得 XMLHttpRequest 的响应?
【发布时间】:2011-03-03 14:33:23
【问题描述】:

我想知道如何使用 XMLHttpRequest 来加载远程 URL 的内容并将访问站点的 HTML 存储在 JS 变量中。

说,如果我想加载和 alert() http://foo.com/bar.php 的 HTML,我该怎么做?

【问题讨论】:

标签: javascript xmlhttprequest


【解决方案1】:

当XMLHttpRequest.readyState 等于XMLHttpRequest.DONE 时,您可以通过XMLHttpRequest.responseText 在XMLHttpRequest.onreadystatechange 中获得它。

这是一个示例(与 IE6/7 不兼容)。

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

为了更好的跨浏览器兼容性,不仅是与 IE6/7,还包括一些特定于浏览器的内存泄漏或错误,以及在触发 ajaxical 请求时减少冗长,您可以使用jQuery。

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

请注意,当不在本地主机上运行时,您必须考虑Same origin policy for JavaScript。您可能需要考虑在您的域中创建一个代理脚本。

【讨论】:

    【解决方案2】:

    使用fetch!

    它更具可读性且易于定制。所有现代浏览器和 Node 都支持它。这是more in depth tutorial

    const url = "https://stackoverflow.com";
    fetch(url)
      .then(
        response => response.text() // .json(), .blob(), etc.
      ).then(
        text => console.log(text) // Handle here
      );
    

    您可以选择传递第二个参数,具体取决于请求的需求/类型。

    // Example request options
    fetch(url, {
      method: 'post', // Default is 'get'
      body: JSON.stringify(dataToPost),
      mode: 'cors',
      headers: new Headers({
        'Content-Type': 'application/json'
      })
    })
    .then(response => response.json())
    .then(json => console.log('Response', json))
    

    在 Node.js 中,您需要使用以下命令导入 fetch:

    const fetch = require("node-fetch");
    

    如果您想同步使用它(在顶级范围内不起作用):

    const json = await fetch(url)
      .then(response => response.json())
      .catch((e) => {});
    

    更多信息:

    Matt Walsh Tutorial

    Mozilla Documentation

    Can I Use

    【讨论】:

    • 这个问题是关于 HTTPS 的,您可能希望避免 'fetch' 用于同步目的
    • 您的评论没有意义...如果您需要同步,请使用 await
    【解决方案3】:

    将XMLHttpRequest 与pure JavaScript 一起使用的简单方法。您可以设置custom header,但根据需要可选使用。

    1。使用 POST 方法:

    window.onload = function(){
        var request = new XMLHttpRequest();
        var params = "UID=CORS&name=CORS";
    
        request.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };
    
        request.open('POST', 'https://www.example.com/api/createUser', true);
        request.setRequestHeader('api-key', 'your-api-key');
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send(params);
    }
    

    您可以使用 POST 方法发送参数。

    2。使用 GET 方法:

    请运行下面的示例,将会得到 JSON 响应。

    window.onload = function(){
        var request = new XMLHttpRequest();
    
        request.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };
    
        request.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
        request.send();
    }

    【讨论】:

    • 对我来说很好。
    • 很好的例子。工作正常。
    【解决方案4】:

    在XMLHttpRequest 中,使用XMLHttpRequest.responseText 可能会引发如下异常

     Failed to read the \'responseText\' property from \'XMLHttpRequest\': 
     The value is only accessible if the object\'s \'responseType\' is \'\' 
     or \'text\' (was \'arraybuffer\')
    

    从 XHR 访问响应的最佳方式如下

    function readBody(xhr) {
        var data;
        if (!xhr.responseType || xhr.responseType === "text") {
            data = xhr.responseText;
        } else if (xhr.responseType === "document") {
            data = xhr.responseXML;
        } else {
            data = xhr.response;
        }
        return data;
    }
    
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            console.log(readBody(xhr));
        }
    }
    xhr.open('GET', 'http://www.google.com', true);
    xhr.send(null);
    

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 2019-04-27
      • 1970-01-01
      相关资源
      最近更新 更多