問題描述
我想知道如何使用 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模板網!