Javascript 如何获取 XMLHttpRequest 的响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3038901/
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
How to get the response of XMLHttpRequest?
提问by Rohan
I'd like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.
我想知道如何使用 XMLHttpRequest 加载远程 URL 的内容并将访问站点的 HTML 存储在 JS 变量中。
Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?
比如说,如果我想加载和 alert() http://foo.com/bar.php的 HTML,我该怎么做?
回答by BalusC
You can get it by XMLHttpRequest.responseTextin XMLHttpRequest.onreadystatechangewhen XMLHttpRequest.readyStateequals to XMLHttpRequest.DONE.
您可以XMLHttpRequest.responseText在等于XMLHttpRequest.onreadystatechange时获得它。XMLHttpRequest.readyStateXMLHttpRequest.DONE
Here's an example (not compatible with IE6/7).
这是一个示例(与 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);
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
为了更好的跨浏览器兼容性,不仅与 IE6/7 兼容,而且为了覆盖一些特定于浏览器的内存泄漏或错误,并且为了减少触发 ajaxical 请求的冗长,您可以使用jQuery。
$.get('http://example.com', function(responseText) {
alert(responseText);
});
Note that you've to take the Same origin policy for JavaScriptinto account when not running at localhost. You may want to consider to create a proxy script at your domain.
请注意,当不在 localhost 上运行时,您必须考虑JavaScript 的同源策略。您可能需要考虑在您的域中创建代理脚本。
回答by Gibolt
I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.
我建议调查一下fetch。它与 ES5 等效并使用 Promises。它更具可读性且易于定制。
const url = "https://stackoverflow.com";
fetch(url)
.then(
response => response.text() // .json(), etc.
// same as function(response) {return response.text();}
).then(
html => console.log(html)
);
In Node.js, you'll need to import fetchusing:
在 Node.js 中,您需要fetch使用以下命令导入:
const fetch = require("node-fetch");
If you want to use it synchronously (doesn't work in top scope):
如果你想同步使用它(在顶级范围内不起作用):
const json = await fetch(url)
.then(response => response.json())
.catch((e) => {});
More Info:
更多信息:
回答by Mayur S
The simple way to use XMLHttpRequestwith pure JavaScript. You can set custom headerbut it's optional used based on requirement.
最简单的方法使用XMLHttpRequest与pure JavaScript。您可以设置,custom header但可以根据需要选择使用。
1. Using POST Method:
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);
}
You can send params using POST method.
您可以使用 POST 方法发送参数。
2. Using GET Method:
2.使用GET方法:
Please run below example and will get an JSONresponse.
请运行以下示例,将获得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();
}
回答by Fizer Khan
In XMLHttpRequest, using XMLHttpRequest.responseTextmay raise the exception like below
在 中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\')
Best way to access the response from XHR as follows
从 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);

