jQuery当完成动态拉取函数调用时 [英] jQuery When Done on dynamically pulled function call
问题描述
我有以下代码:
在site-code.js中
In site-code.js
....
var ajaxContentFunc = $(origin).data("modal-content-handler");
$.when(window[ajaxContentFunc]()).done(function (resp) {
kModal.showContent(resp);
});
在另一个文件中,我具有以下标记和功能
In another file I have the following tag and function
<a href="#" data-modal-content-handler="ajaxContentGeneration">Click Me</a>
....
function ajaxContentGeneration() {
var aProm = $.ajax({
url: "tests/ajax/AjaxTest.aspx",
data: { exampleType: "modal-ajax" },
dataType: "html"
});
aProm.done(function (data) {
console.log("Ajax Loaded!");
var content = $(data).find("#ajax-content");
return aProm;
});
}
我需要将ajaxContentGeneration(可能的方法)的结果填充到变量中,以发送到showContent或换句话说:
I need to populate the result of the ajaxContentGeneration (whatever method that might be) into the variable to send to showContent or in other words:
1)从标记的modal-content-handler数据属性中提取 ajaxContentFunction 名称
1) Pull the ajaxContentFunction Name from the tag's modal-content-handler data attribute
2)调用函数(在本例中为ajaxContentGeneration)
2) Call function (in this case ajaxContentGeneration)
3)等待函数的ajax完成并返回生成的数据(在本例中为html)
3) Wait for the function's ajax to complete and return the data generated (in this case html)
4)完成后,将该值传递给kModal.showContent(---- Here ----);
4) When completed pass that value to kModal.showContent(----Here----);
但是现在我得到了:
1)正确提取ajaxContentFunctionName
1) Pulls ajaxContentFunctionName correctly
2)调用函数(ajaxContentGeneration()函数)
2) Calls Function (ajaxContentGeneration() function)
3)调用kModal.showContent(undefined).之所以过早地调用它,是因为deferred没有正确地等待函数调用完成(在ajax完成之后).
3) Calls kModal.showContent(undefined). This is called prematurely because the deferred isn't correctly waiting for the function call to complete (after the ajax is done).
4)Ajax完成
我在哪里弄糟?
推荐答案
据我所知,您在那里95%.
As far as I can tell, you are 95% there.
使用.then()
而不是.done()
并返回$.ajax().then()
返回的承诺:
Use .then()
instead of .done()
and return the promise returned by $.ajax().then()
:
function ajaxContentGeneration() {
return $.ajax({
url: "tests/ajax/AjaxTest.aspx",
data: { exampleType: "modal-ajax" },
dataType: "html"
}).then(function (data) {
return $(data).find("#ajax-content"); // this will return jQuery
// return $(data).find("#ajax-content").html(); // this will return html
});
}
您可能还可以从顶级调用中清除$.when()
:
You can probably also purge $.when()
from the top-level call :
var ajaxContentFunc = $(origin).data("modal-content-handler");
window[ajaxContentFunc]().then(function (resp) {
// `resp` is whatever was returned by the `return $(data).find()...` statement above
kModal.showContent(resp);
});
我说可能"的原因是,如果可以调用值返回(而非承诺返回)功能而不是ajaxContentGeneration()
,则必须使用$.when()
.
The reason I say "probably" is that $.when()
would be necessary if value-returning (not promise-returning) functions could be called instead of ajaxContentGeneration()
.
这篇关于jQuery当完成动态拉取函数调用时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!