[英]Ajax XmlHttpRequest
I have js code as well as *.txt file with some text that I want to load to the page. 我有js代码以及带有要加载到页面的一些文本的* .txt文件。
JS Code: 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 Code: HTML代码:
<body>
<h1>AjaxTest</h1>
<a href="ajax.txt">Load the text from file</a>
<script src="main.js">
</script>
Everything should work. 一切都应该工作。 However ReSharper underlines XmlHttpRequest(); 但是ReSharper强调XmlHttpRequest(); and says Use of an implicitly declared global variable" and for this xhr.responseText; it says - Expression statement is not assignment of call. What is the problem? 并针对此xhr.responseText说“ 使用隐式声明的全局变量” ;它说-Expression 语句不是调用的赋值。这是什么问题?
A few comments: 一些评论:
Capitalize "XML": 大写“ XML”:
var xhr = new XmlHttpRequest();
-> var xhr = new XMLHttpRequest();
-> var xhr = new XMLHttpRequest();
A variable is not a statement: 变量不是语句:
xhr.responseText;
, just get rid of this line, it's like saying var a = 5;
,摆脱掉这条线,就像说var a = 5;
and then a;
然后a;
You can use document.body
to get the body element: 您可以使用document.body
获取body元素:
var body = document.getElementsByTagName("body")[0];
-> - >
var body = document.body;
You have no variable named hxr
: 您没有名为hxr
变量:
hxr.send(null);
-> xhr.send(null);
-> xhr.send(null);
If you're following this is what you should get: 如果您遵循的是这应该得到的:
(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;
};
})();
If I were you I'd prefer using jQuery: 如果我是我,我宁愿使用jQuery:
$('a').first().click(function() {
$.get('ajax.txt', function(data) {
$(document.body).append('<p>' + data + '</p>');
});
});
This is your entire code using jquery ;) 这是使用jquery的整个代码;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.