3 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊
您正在調(diào)用異步$.get()方法,該異步方法將在您的getPicsInFolder()函數(shù)返回后調(diào)用其回調(diào)函數(shù)。請(qǐng)遵循以下示例中的注釋:
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;
}
您應(yīng)該考慮以某種方式重構(gòu)代碼,以便在$.get()回調(diào)中處理JSON對(duì)象的邏輯。例:
$.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貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
您正在異步獲取數(shù)據(jù)。返回function (data) {}后將調(diào)用回調(diào)函數(shù)getPicsInFolder。
您有兩種選擇:
(錯(cuò)誤的選擇):將ajax調(diào)用設(shè)置為同步。
(正確的選項(xiàng)):重組代碼,以便返回?cái)?shù)據(jù)需要發(fā)生的任何事情都在回調(diào)中發(fā)生。
一種實(shí)現(xiàn)方法是將回調(diào)傳遞給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
});
然后,當(dāng)您調(diào)用getPicsInFolder時(shí),不要這樣做:
pics = getPicsInFolder('foldername');
//do something with pics
做這個(gè):
getPicsInFolder('foldername', function (pics) {
//do something with pics
});

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超9個(gè)贊
AJAX請(qǐng)求應(yīng)該是異步的(你是能夠在停止執(zhí)行,并有效阻止UI的成本做同步的)。
getPicsInFolder()在AJAX請(qǐng)求完成之前返回。您需要更新UI /處理完成事件(作為參數(shù)傳遞給的匿名函數(shù))返回的JSON對(duì)象$.get():
$.get("", function ()
{
// This anonymous function will execute once the request has been completed
// Update your UI/handle your data here
});
假設(shè)我想更新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
});
});
添加回答
舉報(bào)