小编典典

无法从jQuery Ajax调用中获取正确的返回值

javascript

这应该返回一个包含图片文件名列表的JSON对象。带注释的警报显示正确的数据,但alert(getPicsInFolder("testfolder"));显示"error"

function getPicsInFolder(folder) {
  return_data = "error";
  $.get("getpics.php?folder=" + folder, function (data) {
    data = jQuery.parseJSON(data);
    $.each(data, function (index, value) {
      data[index] = "folders/" + folder + "/" + value;
    });
    //alert(data); // This alert shows the correct data, but that's hardly helpful
    return_data = data;
  });
  return return_data;
}

我究竟做错了什么?


阅读 266

收藏
2020-05-01

共1个答案

小编典典

您正在调用异步$.get()方法,该异步方法将在您的getPicsInFolder()函数返回后调用其回调函数。请遵循以下示例中的注释:

function getPicsInFolder(folder) {
   return_data = "error";
   // Since the $.get() method is using the asynchronous XMLHttpRequest, it 
   // will not block execution, and will return immediately after it is called,
   // without waiting for the server to respond.
   $.get("getpics.php", function (data) {
      // The code here will be executed only when the server returns
      // a response to the "getpics.php" request. This may happen several 
      // milliseconds after $.get() is called.
      return_data = data;
   });

   // This part will be reached before the server responds to the asynchronous
   // request above. Therefore the getPicsInFolder() function returns "error".
   return return_data;
}

您应该考虑以某种方式重构代码,以便在$.get()回调中处理JSON对象的逻辑。例:

$.get("getpics.php?folder=test", function (data) {
   // Handle your JSON data in here, or call a helper function that
   // can handle it:
   handleMyJSON(data); // your helper function
});
2020-05-01