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

Dat*_*bot 5 javascript ajax jquery return

这应该返回一个包含图片文件名列表的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;
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Dan*_*llo 10

您正在调用异步$.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;
}
Run Code Online (Sandbox Code Playgroud)

您应该考虑重构代码,使得处理JSON对象的逻辑在$.get()回调中.例:

$.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
});
Run Code Online (Sandbox Code Playgroud)