【问题标题】:Can't get correct return value from an jQuery Ajax call [duplicate]无法从 jQuery Ajax 调用中获得正确的返回值 [重复]
【发布时间】:2011-04-02 00:48:41
【问题描述】:

这应该返回一个包含图片文件名列表的 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;
}

我做错了什么?

【问题讨论】:

    标签: javascript jquery ajax return


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。显然我需要重新思考和重写。
    【解决方案2】:

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

    你有两个选择:

    1. (不好的选择):将您的 ajax 调用设置为同步。

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

    一种方法是将回调传递给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
    });
    

    【讨论】:

      【解决方案3】:

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

      getPicsInFolder() 在 AJAX 请求完成之前返回。您需要更新 UI/处理完整事件返回的 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
          });
      });
      

      【讨论】:

      • 您可以请求 XHR 同步。
      • @stranger: 是的,你可以,但是同步 XHR 不能定义为 AJAX,因为 AJAX 中的 A 是异步的 :)
      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2019-02-25
        • 2013-08-22
        • 1970-01-01
        • 2012-03-28
        • 1970-01-01
        • 1970-01-01
        • 2011-01-28
        • 1970-01-01
        • 2023-03-11
        相关资源
        最近更新 更多