开发者

IE9 - spinner not displaying during ajax request [resolved - don't use Msxml2.XMLHTTP.4.0]

My code is as follows:

  function loadContent() {

    if(loading) { return false; }
    showSpinner();

    var xhr = createXHR();
    xhr.open("GET", "http://localhost/testing.php");
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4) {
        hideSpinner();
        var resp = xhr.responseText;
        document.getElementById("content").innerHTML = resp;
      }
    }
    xhr.send(null);

  }

  function showSpinner() {
    document.getElementById("loadingIcon").style.display = 'inline';
    loading = true;
  }

  function hideSpinner() {
    document.getElementById("loadingIcon").style.display = 'none';
    loading = false;
  }

This works as intended in Firefox and Chrome, but in IE9 the spinner does not display.

I commented out the first line of the hideSpinner() function and found that IE9 does display the spinner, but only after the AJAX request has returned a result. Have I done something out of order here?

[edit] Figured it out-- original code of createXHR() method follows:

  function createXHR() {
    try { return new ActiveXObject("Msxml2.XMLHTTP.5.0"); } catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.4.0"); } catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
    try { return new XMLHttpRequest(); } catch(e) {}
    return null;
  }

Moving the last '开发者_如何学Pythontry' line to the top fixes the problem.


Do not rely on global variables for such a thing. You do not need a loading variable at all.

function loadContent() {
  var spinner = document.getElementById("loadingIcon");
  var xhr = createXHR();

  spinner.style.display = 'inline';

  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        document.getElementById("content").innerHTML = xhr.responseText;
      }
      spinner.style.display = 'none';
    }
  }

  xhr.open("GET", "http://localhost/testing.php");
  xhr.send(null);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜