我一直在尝试获取我的 ajax 请求以保证从我加载的模板中得到响应。
基本上,如果我运行我的代码来返回我的延迟对象 $.then() 在我拥有我的模板对象之前调用。这仅在第一次运行时发生。
我用这个把头发扯掉了!
我的ajax调用:
var ajax = {
getTemplate: (function (id) {
/// <summary>
/// This method when used with $.Deferred fetches a html string
//// containing the template appliciable
/// to the the supplied id.
/// The ajax request object is cached upon the first request and is
/// returned by the cache
/// upon each subsequent request.
/// </summary>
/// <param name="id" type="String">
/// The id that matches the filename to request the template object
/// from.
/// </param>
/// <returns type="jqXHR">
/// A superset of the XMLHTTPRequest object that impliments the
/// promise interface.
/// </param>
var cache = {}; // private cache
// Gets assigned to getTemplate.
return function (id) {
var url = "/templates/" + id + ".tpl";
return cache[id]|| $.ajax({
url: url,
dataType: "html",
success: function (data) {
//ajax.getTemplate(id, data);
cache[id] = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
log("template request " + id,
XMLHttpRequest,
textStatus,
errorThrown);
}
});
};
} ())
};
我在我的方法中这样调用它:
$.when(ajax.getTemplate("tooltip-attributes")()).then(function (template) {
if (template) {
// Do my template stuff here.
}
});