鍍金池/ 問(wèn)答/HTML/ 大佬們幫忙看看我這ajax哪里寫(xiě)錯(cuò)了?

大佬們幫忙看看我這ajax哪里寫(xiě)錯(cuò)了?

我是模仿MDN上面這個(gè)頁(yè)面的step3中的例子寫(xiě)的:
鏈接描述

這個(gè)是例子的代碼:

<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>

我運(yùn)行這個(gè)例子沒(méi)有問(wèn)題,但是我模仿它的代碼提示我未定義變量,我的代碼部分:

function loadPage(userType, id){
    if (userType==="普通用戶(hù)") {
        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行是函數(shù)alertContents 里的第一行,我看了半天,沒(méi)找到的代碼和例子差在哪里,求大佬指教!

回答
編輯回答
裸橙

function alertContents 里,是httpRequest.readyState不是req.readyState。httpRequest在例子里是在外層定義了的。

2018年7月8日 13:02
編輯回答
莓森

var req = new XMLHttpRequest();這個(gè)拿到最外面試試?
你的alertContents這個(gè)函數(shù)獲取不到你定義的req啊

2018年7月7日 11:06
編輯回答
莓森

函數(shù)作用域的問(wèn)題,req這個(gè)變量定義在loadPage這個(gè)函數(shù),在 alertContents函數(shù)里訪問(wèn)不到。 最好不要在if里定義變量

2017年4月21日 15:01