【发布时间】:2015-12-09 06:03:11
【问题描述】:
我目前正在使用 JavaScript 尝试以纯文本形式获取网页内容,并将文本转储为字符串。
我找到了很多方法来做到这一点,但是当我做类似的事情时似乎什么也没发生:(在这个例子中,我使用纯文本文件)
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
// As you can see I'm also spamming myself with alerts, but they also
// just return blank.
alert(xmlhttp.response);
}
xmlhttp.open("GET", "http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt", true);
xmlhttp.send();
我该怎么做?
【问题讨论】:
-
提个建议 - 使用
console.log而非alert进行调试。 -
@JonathanBrooks 感谢您的回复。我只使用
alert(),因为我迫不及待地想看看执行时发生了什么。 (我正在使用括号) -
您是否在与
XMLHttpRequest相同的域上运行此代码?否则很可能是由于同源策略错误 -
@JonathanBrooks 是的。谢谢,答案还指出,我相信这是手头的错误。
标签: javascript html string http xmlhttprequest