我有js代码和*.txt文件,还有一些我想要加载到页面中的文本。
JS代码:
(function () {
var link = document.getElementsByTagName("a")[0];
link.onclick = function () {
var xhr = new XmlHttpRequest();
xhr.onreadystatechange = function () {
if ((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)) {
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
}
};
xhr.open("Get", "ajax.txt", true);
hxr.send(null);
return false;
};
})();
HTML代码:
<body>
<h1>AjaxTest</h1>
<a href="ajax.txt">Load the text from file</a>
<script src="main.js">
</script>
一切都应该正常。然而,XmlHttpRequest();强调xhr.responseText;,并表示使用隐式声明的全局变量“,对于这个xhr.responseText;,它说-表达式语句不是调用的赋值。,问题是什么?”
发布于 2014-04-13 17:46:32
几点意见:
var xhr = new XmlHttpRequest();
-> var xhr = new XMLHttpRequest();
xhr.responseText;
,把这行去掉,就像说var a = 5;
,然后说a;
document.body
获取body元素:
var body = document.getElementsByTagName("body")[0];
->
var body = document.body;
hxrhxr.send(null);
-> xhr.send(null);
的变量。如果你在跟踪这是你应该得到的:
(function () {
var link = document.getElementsByTagName("a")[0];
link.onclick = function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)) {
var body = document.body;
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
}
};
xhr.open("Get", "ajax.txt", true);
xhr.send(null);
return false;
};
})();
如果我是你,我宁愿使用使用jQuery:
$('a').first().click(function() {
$.get('ajax.txt', function(data) {
$(document.body).append('<p>' + data + '</p>');
});
});
--这是使用jquery ;)的全部代码
https://stackoverflow.com/questions/23045870
复制相似问题