我想知道如何使用 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.responseText 在 XMLHttpRequest.onreadystatechange 当 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 的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
即使在调用 abort (jQuery) 之后,浏览器也会等待Browser waits for ajax call to complete even after abort has been called (jQuery)(即使在调用 abort (jQuery) 之后,浏览器也会等待 ajax 调用
JavaScript innerHTML 不适用于 IE?JavaScript innerHTML is not working for IE?(JavaScript innerHTML 不适用于 IE?)
XMLHttpRequest 无法加载,请求的资源上不存在“AXMLHttpRequest cannot load, No #39;Access-Control-Allow-Origin#39; header is present on the requested resource(XMLHttpRequest 无法加载,请求的资
XHR HEAD 请求是否有可能不遵循重定向 (301 302)Is it possible for XHR HEAD requests to not follow redirects (301 302)(XHR HEAD 请求是否有可能不遵循重定向 (301 302))
NETWORK_ERROR:XMLHttpRequest 异常 101NETWORK_ERROR: XMLHttpRequest Exception 101(NETWORK_ERROR:XMLHttpRequest 异常 101)
XMLHttpRequest 206 部分内容XMLHttpRequest 206 Partial Content(XMLHttpRequest 206 部分内容)