innerHTML works in IE and Firefox, but not Chrome

天涯浪子 提交于 2019-12-01 15:52:45

问题


The data will not display in Chrome, unless i open an IE tab in Chrome go to the site then close it back to Chrome (sorry, if that doesn't make much sense).

window.onload = function() {
    var url = "http://----.freeiz.com/gbSales/sales.json";
    var request = new XMLHttpRequest();
    request.open("GET", url);
    request.onload = function () {
        if (request.status == 200) {
            updateSales(request.responseText);
        }
    };
    request.send(null);
}
function updateSales(responseText) { 
    var salesDiv = document.getElementById("sales");
    salesDiv.innerHTML = responseText;
}

Im just starting to learn JavaScript so I really don't know much about it.


回答1:


You should use some modern Javascript library. It guards you from many of those small differences between browsers. I like jQuery.

So, with jquery your code

window.onload = function() {
  var url = "http://----.freeiz.com/gbSales/sales.json";
  var request = new XMLHttpRequest();
  request.open("GET", url);
  request.onload = function () {
    if (request.status == 200) {
      updateSales(request.responseText);
    }
  };
  request.send(null);
}
function updateSales(responseText) { 
  var salesDiv = document.getElementById("sales");
  salesDiv.innerHTML = responseText;
}

becomes

$(document).load(function() {
  var url = "http://----.freeiz.com/gbSales/sales.json";

  $.get(url, {}, function(data) {
    $('#sales').html(data);
  });
});

Shorter, cleaner and works in all browsers!




回答2:


I think you want to use:

request.onreadystatechange = function() {

instead of:

request.onload = function() {

And change the way you check the return value.

See the asynchronous request code example here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Using_XMLHttpRequest for more details.




回答3:


Just find that only the first form tag is removed so you can put an empty form () and the next one is keep in the code.



来源:https://stackoverflow.com/questions/8621278/innerhtml-works-in-ie-and-firefox-but-not-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!