如何获得 XMLHttpRequest 的响应?

2022-01-15 00:00:00 xmlhttprequest javascript

我想知道如何使用 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.

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

Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?

推荐答案

你可以通过XMLHttpRequest.responseTextXMLHttpRequest.onreadystatechangeXMLHttpRequest.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.

相关文章