我想重寫代碼從How to capture asynchronous ajax response into a variable?使用jQuery的延期功能。我開始:基本jQuery延遲使用ajax
var html ="";
$.ajax({
type:"POST",
url: "Ajax/getHtml",
data: { u : contents },
dataType: 'html',
success: function(data) {
html = data;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(jqXHR,textStatus, errorThrown);
}
});
console.log('html', html);
我試圖把它變成一個延遲功能,可以返回所請求的HTML頁面時得到解決。我一直在閱讀http://learn.jquery.com/code-organization/deferreds/examples/和http://jqfundamentals.com/chapter/ajax-deferreds這樣做。到目前爲止,我想出了:
var html_response = new $.Deferred(url){
$.ajax({
type:"POST",
url: "Ajax/getHtml",
data: { u : url},
dataType: 'html',
success: html_response.resolve,
error: html_response.reject
});
};
這將用作部分:
html_response().done{
console.log('html', html);
}
我所試圖做的是當get_html功能HTML返回成功地(即get_html解決)抓住html並將其發送到控制檯。我很難弄清楚如何把這些碎片放在一起。請有人給我建議。
將ajax放入函數中並返回$ .ajax()對象 – Neve12ende12 2015-01-26 18:58:42
'$ .ajax'自身返回一個承諾。無需創建自己的延期。 – atomman 2015-01-26 18:59:57