XMLHttpRequest.onReadyStateChange在Chrome,Firefox,Internet Explorer

时间:2017-01-27 13:12:39

标签: json ajax xmlhttprequest onreadystatechange

我正在使用Aptana Studio 3文本编辑器并在Windows 7企业操作系统上工作。我有以下AJAX代码,它不能在本地系统上运行以获取保存在https网站上的JSON文件。此示例取自Youtube视频:

JSON and AJAX Tutorial: With Real Examples

的index.html:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta name="test" content="content"/>
        <title>JSON and AJAX</title></head>
<header>
  <h1>JSON and AJAX</h1>
  <link rel="stylesheet" href="styles.css" type="text/css" media="screen" title="no title" charset="utf-8"/>
</header>


<body>
 <script src="main.js"></script>
 <button type="button" onclick="function()" id="btn">Fetch Info for 3 New Animals</button>
 <div id="animal-info"> </div>
</body>

</html>

Styles.css中:

    html, body {
  padding: 0;
  margin: 0;
}

.hide-me {
  visibility: hidden;
  opacity: 0;
  transform: scale(.75);
}

h1 {
  margin-top: 0;
  font-size: 2.4em;
  font-weight: normal;
  display: inline-block;
}

body {
  font-family: Helvetica, sans-serif;
  padding: 50px 10%;
}

button {
  background-color: #046380;
  color: #FFF;
  border: none;
  padding: 10px 15px;
  font-size: 15px;
  border-radius: 4px;
  cursor: pointer;
  outline: none;
  box-shadow: 2px 2px 0 #034154;
  margin-bottom: 10px;
  margin-left: 18px;
  transition: opacity .4s ease-out, transform .4s ease-out, visibility .4s ease-out;
  position: relative;
  top: -10px;
}

button:hover {
  background-color: #034F66;
}

button:active {
  background-color: #034154;
  box-shadow: none;
  position: relative;
  top: -8px;
  left: 2px;
}

p {
  padding: 4px 0 2px 8px;
  line-height: 1.7;
  border-bottom: 1px dotted #DDD;
  list-style: none;
  margin: 0;
}

main.js:

    var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");

btn.addEventListener("onClick", function() {  
  var ourRequest = new XMLHttpRequest();
  ourRequest.open("GET", "https://learnwebcode.github.io/json-example/animals-" + pageCounter + ".json");
  //ourRequest.open('GET', 'animals-' + pageCounter + '.json');
  ourRequest.onload = function() {
    if (ourRequest.status >= 200 && ourRequest.status < 400) {
      var ourData = JSON.parse(ourRequest.responseText);
      renderHTML(ourData);
    } else {
      console.log("We connected to the server, but it returned an error.");
    }

  };

  ourRequest.onerror = function() {
    console.log("Connection error");
  };

  ourRequest.send();
  pageCounter++;
  if (pageCounter > 3) {
    btn.classList.add("hide-me");
  }
}
);


function renderHTML(data) {
  var htmlString = "";

    for (i = 0; i < data.length; i++) {
    htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";

    for (ii = 0; ii < data[i].foods.likes.length; ii++) {
      if (ii == 0) {
        htmlString += data[i].foods.likes[ii];
      } else {
        htmlString += " and " + data[i].foods.likes[ii];
      }
    }

    htmlString += ' and dislikes ';

    for (ii = 0; ii < data[i].foods.dislikes.length; ii++) {
      if (ii == 0) {
        htmlString += data[i].foods.dislikes[ii];
      } else {
        htmlString += " and " + data[i].foods.dislikes[ii];
      }
    }

    htmlString += '.</p>';

  }

  animalContainer.insertAdjacentHTML('beforeend', htmlString);
}

此代码似乎不适用于我的本地计算机。我尝试在我的本地机器上使用 NodeJs 安装一个http服务器来运行它,但仍然没有乐趣!

ww3Schools.com

上的另一个JSON AJAX代码

虽然似乎工作正常。这是html文件中的内联javascript代码。最初我认为onReadyStateChange是不能在IE,FF,CH等上工作的罪魁祸首,但这个网站代码也有onReadyStateChange,但它工作正常!

或者它是Button click事件处理程序导致它无效的原因吗?

btn.addEventListener("onClick", function() {  

我的代码不是内联的,这可能是原因吗?如果没有,我错过了什么或做错了什么?

2 个答案:

答案 0 :(得分:0)

我通过移动&#34; div&#34;修改了html文件以上&#34;脚本&#34;标记:

<强>的index.html:

    <!DOCTYPE html>
<html>
    <head>
        <meta name="test" content="content"/>
        <title>JSON and AJAX</title></head>
<header>
  <h1>JSON and AJAX</h1>
  <link rel="stylesheet" href="styles.css" type="text/css" media="screen" title="no title" charset="utf-8"/>
 <button type="button" onclick="function()" id="btn">Fetch Elements</button>
 <div id="animal-info"> </div>
</header>

<body>
 <script src="main.js"></script>
</body>

</html>

<强> main.js:

var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");

  btn.addEventListener("click", function() {  
  // function LoadJSON() {
      if (window.XMLHttpRequest) {
        // code for modern browsers
        var ourRequest = new XMLHttpRequest();
        } else {
        //code for IE6, IE5
        var ourRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }

      // ourRequest.onLoad = function() {    
      ourRequest.onreadystatechange = function() {
          if (this.readyState = 4 && (this.status >= 200 && this.status < 400)) {
            var ourData = JSON.parse(ourRequest.responseText);
            renderHTML(ourData);
            } else {
            console.log("We connected to the server, but it returned an error.");
          }
      };

      ourRequest.open("GET", "https://learnwebcode.github.io/json-example/animals-" + pageCounter + ".json");
      // ourRequest.open('GET', 'animals-' + pageCounter + '.json');
      ourRequest.send();

      ourRequest.onerror = function() {
      console.log("Connection error");
      };

      pageCounter++;
      if (pageCounter > 3) {
        btn.classList.add("hide-me");
      }
  }
);

function renderHTML(data) {
  var htmlString = "";
    for (i = 0; i < data.length; i++) {
        htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";

            for (ii = 0; ii < data[i].foods.likes.length; ii++) {
              if (ii == 0) {
                htmlString += data[i].foods.likes[ii];
              } else {
                htmlString += " and " + data[i].foods.likes[ii];
              }
            }
            htmlString += ' and dislikes ';

            for (ii = 0; ii < data[i].foods.dislikes.length; ii++) {
              if (ii == 0) {
                htmlString += data[i].foods.dislikes[ii];
              } else {
                htmlString += " and " + data[i].foods.dislikes[ii];
              }
            }   
            htmlString += '.</p>';
        }
        // animalContainer.insertAdjacentHTML('beforeend', htmlString);
        animalContainer.innerHTML=htmlString;
}

现在可以使用了!

我面临的唯一问题是如果我在服务器上有更多的json文件,我如何根据处理的json文件的数量隐藏(&#34; hide-me&#34;)按钮是点击了一次没有?

现在,如果pageCounter超过3,它会隐藏按钮。

      if (pageCounter > 3) {
    btn.classList.add("hide-me");
  }

我看到的另一个问题是,如果我启用&#34; insertAdjacentHTML&#34;,它会显示每个json两次。为什么会这样?

// animalContainer.insertAdjacentHTML('beforeend', htmlString);

答案 1 :(得分:0)

使用此:

btn.style.visibility =&#34;隐藏&#34 ;;