[英]Returning result from jquery ajax request to a variable rather than firing a function
我正在嘗試使用jquery進行MCV。 我正在對返回數據的api進行調用-我要做的是將數據返回到變量中,而不是在模型中調用additioanl函數。 以下代碼雖然不能滿足我的期望(the_data = result) 。 有什么想法可以實現這一目標嗎?
function lookForSomething()
{
var the_data = $.ajax({ type: "GET",
url: TheUrl,
dataType: "jsonp",
success: function(result) { return result; }
});
return the_data;
}
非常感謝,J
如果正確理解,則希望TheUrl返回的數據為lookForSomething的返回值。
從技術上講,您可以使用async選項執行此操作:
function lookForSomething()
{
var the_data;
$.ajax({ type: "GET",
url: TheUrl,
dataType: "jsonp",
async : false,
success: function(result) { the_data = result; }
});
return the_data;
}
我強烈敦促您不要這樣做。 它不像Javascript一樣,它將在運行時鎖定用戶的瀏覽器。 將回調函數傳遞給函數並success
調用它會更好。
您可能正在尋找延遲對象 :
function lookForSomething()
{
var the_data;
$.when(
$.ajax({ type: "GET",
url: TheUrl,
dataType: "jsonp",
success: function(result) { the_data=result; }
});
).done(function() {
return the_data;
}).fail(function() {
return '';
});
}
請記住,這仍然是異步的,因此當您調用var ddd = lookForSomething();
,ddd將沒有您期望的值,因為該調用可能仍在運行。 我$.when()
的唯一原因是因為您似乎需要很多依賴項。 $.when()
允許您等待多個ajax命令 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.