如何获得XMLHttpRequest的响应? [英] How to get the response of XMLHttpRequest?
问题描述
我想知道如何使用XMLHttpRequest加载远程URL的内容,并将访问过的站点的HTML存储在JS变量中。
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.
比如说,如果我想加载并提醒() http://foo.com/bar.php的HTML a>,我该怎么做?
Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?
推荐答案
你可以通过 XMLHttpRequest.responseText
自由软件网站管当 XMLHttpRequest.readyState
等于 XMLHttpRequest.DONE
。
这是一个例子(与IE6 / 7不兼容)。
Here's an example (not compatible with 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 。
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.
$.get('http://example.com', function(responseText) {
alert(responseText);
});
请注意,您必须使用与JavaScript相同的原始策略。您可能需要考虑在您的域中创建代理脚本。
Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.
这篇关于如何获得XMLHttpRequest的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!