我是模仿MDN上面这个页面的step3中的例子写的:
链接描述
这个是例子的代码:
<button id="ajaxButton" type="button">Make a request</button>
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'test.html');
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
我运行这个例子没有问题,但是我模仿它的代码提示我未定义变量,我的代码部分:
function loadPage(userType, id){
if (userType==="普通用户") {
var req = new XMLHttpRequest();
if (!req) {
alert('Giving up :( cannot create an XMLHTTP instance');
return false;
}
req.onreadystatechange = alertContents;
req.open("GET", "edit.php?id="+id);
req.send();
}else{
var req = new XMLHttpRequest();
if (!req) {
alert('Giving up :( cannot create an XMLHTTP instance');
return false;
}
req.onreadystatechange = alertContents;
req.open("GET", "readonly.php?id"+id);
req.send();
}
}
function alertContents(){
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status === 200) {
document.getElementById('sectionDetail').innerHTML = req.requestText;
}else{
alert('there was a problem with the request.');
}
}else{
alert('there was a problem');
}
}
然后console提示:
29行是函数alertContents 里的第一行,我看了半天,没找到的代码和例子差在哪里,求大佬指教!