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

IT技术 javascript jquery ajax return
2021-01-26 22:06:39

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

您正在调用异步$.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
});
谢谢你。显然,我需要重新思考并重写它。
2021-04-12 22:06:39

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

您有两个选择:

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

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
    });
});
@stranger:确实可以,但是根据定义,同步 XHR 不能是 AJAX,因为 AJAX 中的 A 用于异步:)
2021-03-18 22:06:39
您可以请求同步 XHR。
2021-03-26 22:06:39

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