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

时间:2022-10-18 07:51:24

This question already has an answer here:

这个问题在这里已有答案:

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".

这应该返回一个包含图片文件名列表的JSON对象。注释警报显示正确的数据,但警告(getPicsInFolder(“testfolder”));显示“错误”。

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?

我究竟做错了什么?

4 个解决方案

#1


10  

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:

您正在调用异步$ .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;
}

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

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


3  

You're getting the data asynchronously. The callback function function (data) {} is called after getPicsInFolder returns.

你是异步获取数据的。在getPicsInFolder返回后调用回调函数函数(data){}。

You have two options:

你有两个选择:

  1. (the bad option): set your ajax call to be synchronous.

    (坏选项):将您的ajax调用设置为同步。

  2. (the right option): restructure your code, so that anything that needs to happen with the return data happens in the callback.

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

One way to do this would be to pass a callback into getPicsInFolder, like this:

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

Then, when you call your getPicsInFolder, instead of doing:

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

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

do this:

做这个:

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

#3


1  

AJAX requests should be asynchronous (you are able to do synchronous ones at the cost of halting execution and in effect blocking your UI).

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

getPicsInFolder() is returning before the AJAX request has completed. You need to update you UI/handle the JSON object returned on the complete event (the anonymous function you are passing as an argument to $.get()):

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

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

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

Say I wanted to update an element in my UI...

说我想更新我的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
    });
});

#4


0  

You're confused about how AJAX works. The data is not available until the request has completed, which happens after the function has returned. And the data is only available within the callback.

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

#1


10  

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:

您正在调用异步$ .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;
}

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

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


3  

You're getting the data asynchronously. The callback function function (data) {} is called after getPicsInFolder returns.

你是异步获取数据的。在getPicsInFolder返回后调用回调函数函数(data){}。

You have two options:

你有两个选择:

  1. (the bad option): set your ajax call to be synchronous.

    (坏选项):将您的ajax调用设置为同步。

  2. (the right option): restructure your code, so that anything that needs to happen with the return data happens in the callback.

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

One way to do this would be to pass a callback into getPicsInFolder, like this:

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

Then, when you call your getPicsInFolder, instead of doing:

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

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

do this:

做这个:

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

#3


1  

AJAX requests should be asynchronous (you are able to do synchronous ones at the cost of halting execution and in effect blocking your UI).

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

getPicsInFolder() is returning before the AJAX request has completed. You need to update you UI/handle the JSON object returned on the complete event (the anonymous function you are passing as an argument to $.get()):

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

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

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

Say I wanted to update an element in my UI...

说我想更新我的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
    });
});

#4


0  

You're confused about how AJAX works. The data is not available until the request has completed, which happens after the function has returned. And the data is only available within the callback.

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