函数返回javascript中的字符串

函数返回javascript中的字符串,javascript,Javascript,我正试图使用一个函数调用一个ajax请求到我的服务器以获取json数据。如果我在ajax函数中执行resp变量,它将成功显示数据。如果我尝试将ajax函数设置为一个变量,然后控制该变量,它将返回未定义的。有没有想法让函数请求数据,然后将ti设置为一个变量以进行控制 function jsonData(URL) { var xhr = new XMLHttpRequest(); xhr.open("GET", URL, true); xhr.onreadystatechange = functio

我正试图使用一个函数调用一个ajax请求到我的服务器以获取json数据。如果我在ajax函数中执行
resp
变量,它将成功显示数据。如果我尝试将ajax函数设置为一个变量,然后控制该变量,它将返回未定义的。有没有想法让函数请求数据,然后将ti设置为一个变量以进行控制

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);

这其实很简单。。将您的呼叫更改为通过同步

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); });

这其实很简单。。将您的呼叫更改为通过同步

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); });