无法从 jQuery Ajax 调用中获得正确的返回值 [英] Can't get correct return value from an jQuery Ajax call

查看:25
本文介绍了无法从 jQuery Ajax 调用中获得正确的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is supposed to return a JSON object containing a list of picture filenames. The commented alert shows the correct data, but alert(getPicsInFolder("testfolder")); shows "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;
}

我做错了什么?

推荐答案

您正在调用异步$.get() 方法,它的回调函数将在 getPicsInFolder() 函数返回后调用.按照以下示例中的注释进行操作:

You are calling the asynchronous $.get() method, where its callback function will be called after your getPicsInFolder() function returns. Follow the comments in the example below:

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

您应该考虑重构您的代码,以便处理 JSON 对象的逻辑位于 $.get() 回调中.示例:

You should consider refactoring your code in such a way that the logic to handle the JSON object is in the $.get() callback. Example:

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

这篇关于无法从 jQuery Ajax 调用中获得正确的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆