3 回答

TA貢獻1796條經驗 獲得超7個贊
您正在調用異步$.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
});

TA貢獻1836條經驗 獲得超13個贊
您正在異步獲取數據。返回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
});

TA貢獻1784條經驗 獲得超9個贊
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
});
});
添加回答
舉報