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

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

}

我究竟做错了什么?


慕慕森
浏览 754回答 3
3回答

芜湖不芜

您正在调用异步$.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;}您应该考虑以某种方式重构代码,以便在$.get()回调中处理JSON对象的逻辑。例:$.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});

开心每一天1111

您正在异步获取数据。返回function (data) {}后将调用回调函数getPicsInFolder。您有两种选择:(错误的选择):将ajax调用设置为同步。(正确的选项):重组代码,以便返回数据需要发生的任何事情都在回调中发生。一种实现方法是将回调传递给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    });});
打开App,查看更多内容
随时随地看视频慕课网APP