如何获取XMLHttpRequest的响应?

245
我想知道如何使用XMLHttpRequest来加载远程URL的内容,并将所访问站点的HTML存储在JS变量中。
比如说,如果我想要加载并alert() http://foo.com/bar.php 的HTML,我该怎么做?

可能是XMLHttpRequest中缺少的内容是什么?的重复问题。 - Noah Witherspoon
3
如果您使用JS库,jQuery的.load()方法可以让这个过程更加简单:http://api.jquery.com/load/。 - scunliffe
31
谢天谢地,终于找到一个不涉及 jQuery 的 Google 结果 :| - Sam Vloeberghs
4个回答

344

XMLHttpRequest.readyState等于XMLHttpRequest.DONE时,您可以通过XMLHttpRequest.onreadystatechange中的XMLHttpRequest.responseText获取它。

以下是一个示例(不兼容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,而且可以解决一些特定浏览器的内存泄漏或错误,并且在触发ajax请求时减少冗余,您可以使用jQuery

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

请注意,当不在本地主机上运行时,您必须考虑JavaScript的同源策略。您可能需要考虑在您的域名下创建代理脚本。


48

使用fetch

它更易读且可自定义。所有现代浏览器和Node都支持它。这里有一个更深入的教程

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教程

Mozilla文档

Can I Use


2
这个问题涉及HTTPS,为了同步目的,您可能需要避免使用“fetch”。 - Peko Chan
你的评论没有意义...如果你需要同步,请使用await。 - Gibolt

38

使用纯JavaScript简单地使用XMLHttpRequest的方法。你可以设置自定义头部信息,但仅限于根据需求选择。

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


1
对我来说运行良好。 - Mayur Shedage
好的例子。运行良好。 - user10150997

20

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

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