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

时间:2010-08-21 11:26:38

标签: javascript jquery ajax 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;
}

我做错了什么?

4 个答案:

答案 0 :(得分: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;
}

您应该考虑重构代码,使得处理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
});

答案 1 :(得分:3)

您正在异步获取数据。在function (data) {}返回后调用回调函数getPicsInFolder

您有两种选择:

  1. (错误选项):将您的ajax调用设置为同步。

  2. (正确的选项):重构您的代码,以便回调数据中需要发生的任何事情都发生在回调中。

  3. 执行此操作的一种方法是将回调传递到getPicsInFolder,如下所示:

    function getPicsInFolder(folder, callback) {
        return_data = "error";
        $.get("getpics.php?folder=" + folder, function (data) {
            data = jQuery.parseJSON(data);
            $.each(data, function (index, value) {
                data[index] = "folders/" + folder + "/" + value;
            });
         callback(data); //pass data into the callback function
    });
    

    然后,当你调用你的getPicsInFolder时,而不是:

    pics = getPicsInFolder('foldername');
    //do something with pics
    

    这样做:

    getPicsInFolder('foldername', function (pics) {
        //do something with pics
    });
    

答案 2 :(得分:1)

AJAX请求应该是异步的( 能够以停止执行为代价执行同步请求,实际上阻止了您的UI)。

在AJAX请求完成之前,

getPicsInFolder()正在返回。您需要更新UI /处理在complete事件上返回的JSON对象(您将作为参数传递给$.get()的匿名函数):

$.get("", function ()
{
    // This anonymous function will execute once the request has been completed

    // Update your UI/handle your data here
});

说我想更新我的UI中的元素......

$("#ID-of-a-button-in-the-UI").click(function () // executes on click
{
    $.get("url-to-JSON-object", function (json) // executes on request complete
    {
        $("#ID-of-element-to-update").html(json.rows[0].key); // updates UI
    });
});

答案 3 :(得分:0)

你对AJAX的运作方式感到困惑。在请求完成之前,数据不可用,这在函数返回后发生。并且数据仅在回调中可用。