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 的响应?


基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01