How to get the response of XMLHttpRequest?(如何获得 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.
说,如果我想加载和 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 的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获得 XMLHttpRequest 的响应?


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01