无法通过Javascript获得ajax的答案

时间:2015-06-10 16:25:26

标签: javascript ajax

我有这个:

var something = makeRequest(url);

function makeRequest(url) {

  var http_request = false;

  if (window.XMLHttpRequest) {
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) {
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }

  if (!http_request) {
    console.log('Falla :( No es posible crear una instancia XMLHTTP');
    return false;
  }

  http_request.onreadystatechange = alertContents;
  http_request.open('GET', url, true);
  http_request.send(null);


  function alertContents() {

    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        //console.log(http_request.responseText); //this show a string result
        //return http_request.responseText; //this not return nothing
        //var something = http_request.responseText; // this return a undefined variable
      } else {
        console.log('Hubo problemas con la petición.');
      }
    }
  }
}

看看" if(http_request.status == 200)"我证明和没有的三件事。

我不知道如何退出通话功能。请帮帮我

1 个答案:

答案 0 :(得分:0)

您的alertContents()函数是异步执行的。您无法从函数返回值。您可以声明一个全局变量并为其指定reponseText值,然后对其进行处理。

input()