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

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

问题描述

这应该返回包含图片的文件名列表的JSON对象。该评论警报显示正确的数据,但警报(getPicsInFolder(testfolder)); 节目错误

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

我是什么做错了吗?

What am I doing wrong?

推荐答案

您所呼叫的异步 $获得() 的方法,它的回调函数将你的 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;
}

您应该考虑重构你的code以这样的方式的逻辑来处理JSON对象是在 $。获得()回调。例如:

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天全站免登陆