2012-11-14 143 views
0

我想调用一个ajax请求到我的服务器使用函数的json数据。如果我在ajax函数内部调出resp变量,它将成功显示数据。如果我尝试将ajax函数设置为变量,然后控制该变量,则返回undefined。任何想让这个函数请求数据然后将ti设置为一个变量来解决的想法?函数返回javascript中的字符串

function jsonData(URL) { 
var xhr = new XMLHttpRequest(); 
xhr.open("GET", URL, true); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4) { 
    var resp = JSON.parse(xhr.responseText); 
    return resp; 
    } 
} 
xhr.send(); 
} 

jsonString = jsonData(http://mywebsite.com/test.php?data=test); 

console.log(jsonString); 

回答

3

这其实是非常简单的方式。更改通过同步您的来电..

xhr.open("GET", URL, false); 

话虽这么说,这将阻止浏览器,直到操作已完成,如果你可以使用一个回调相反,它可能会是首选。

function jsonData(URL, cb) { 
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", URL, true); 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4) { 
     var resp = JSON.parse(xhr.responseText); 
     cb(resp); 
    } 
    } 
    xhr.send(); 
} 

jsonData("http://mywebsite.com/test.php?data=test" 
     , function(data) { console.log(data); });