2016-11-06 140 views
0

我写了一个函数,它从php文件中获取一些数据。当我解析它并使用警告框来显示它时,它工作正常,但是当我尝试返回未定义的值时。我不知道为什么会发生这种情况Javascript函数返回null

function getUser() { 

    var httpRequest = new createAjaxRequestObject(); 

    httpRequest.open('GET', 'getUser.php', true); 
    var name; 

    httpRequest.onreadystatechange = function() { 

     if (httpRequest.readyState == 4) { 

      if (httpRequest.status == 200) { 
       name = JSON.parse(httpRequest.responseText); 
       alert(name); //this works just fine and display the name john 
      } else { 
       alert('Problem with request'); 
      } 
     } 
    } 

    httpRequest.send(); 
    return name; //however this is returning null 
} 
+0

阿贾克斯是异步的 - 你返回名称变量,但Ajax请求尚未完成设置。 –

回答

3

现在它发送空值,因为它调用httpRequest.send();后就立即返回值。

在这种情况下,你需要传递一个回调函数将接收返回值

更改这个样子,

function foo(callback) { 
    httpRequest = new XMLHttpRequest(); 
    httpRequest.onreadystatechange = function() { 
     if (httpRequest.readyState === 4) { // request is done 
      if (httpRequest.status === 200) { // successfully 
       callback(httpRequest.responseText); // we're calling our method 


      } 
     } 
    }; 
    httpRequest.open('GET', 'getUser.php', true); 
    httpRequest.send(); 
} 

foo(function (result) { 
    var name = result; 
});