0

下面的脚本有什么问题。这里警报“33here”即将到来,但没有得到我的 json 对象。alert(jsontext)即将出现空白。如果我在浏览器中点击此 URL,那么我将获得 JSON 对象。

    xmlHttp = new XMLHttpRequest();
    xmlHttp.overrideMimeType("application/json");  
    alert('11here');
    xmlHttp.open( "GET", "http://<hostname>/appsuite/api/login", true );
    alert('22here');
    alert(xmlHttp);
    xmlHttp.send();
    alert('33here');
    var jsontext= xmlHttp.responseText;

    alert(jsontext);

根据建议尝试但没有工作。我是 javascript/ajax 的新手。这有什么问题吗?

    xmlHttp = new XMLHttpRequest();
    xmlHttp.overrideMimeType("application/json");  
    alert('Hi 11here');
    xmlHttp.open( "GET", "http://<hostname>/appsuite/api/login", true );
    alert('Hi 22here');
    alert(xmlHttp);
    xmlHttp.send();
    alert('Hi 33here');
    xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        alert(xmlHttp.responseText);
        }
    }
4

2 回答 2

0

Ajax 以异步方式运行。您不能依赖请求.open何时完成,甚至它是否会完成。任何依赖于 ajax 请求值的代码都必须在请求回调中完成。

xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        alert(xmlHttp.responseText);
    }
}
于 2013-06-03T14:57:22.847 回答
0

一个好的起点是查看 MDN 提供的示例:https ://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

function alertContents(httpRequest) {
  try {
    if (httpRequest.readyState === 4) {
     if (httpRequest.status === 200) {
        alert(httpRequest.responseText);
     } else {
        alert('There was a problem with the request.');
      }
    }
  }
   catch( e ) {
     alert('Caught Exception: ' + e.description);
  }
}

在请求状态达到 200 且就绪状态为 4 后,响应被填充。

于 2013-06-03T15:03:05.727 回答