【发布时间】:2014-11-22 12:14:24
【问题描述】:
我正在构建一个仪表板,用户可以在其中添加贡献者的详细信息,然后为该贡献者的一个或多个博客输入数据。
每个博客都通过使用 JSONP 的 api 调用添加到数据库中。 (请求中需要 JSONP 回调函数名称。)因此,当用户单击“添加博客”按钮时,会调用 AddBlog 函数 - 这会进行一些客户端验证并发送 ajax 请求。它还将 ajax 请求添加到数组中。
回调函数 cbAddBlog 会根据服务器返回的任何错误进行更多验证。
因此,当所有博客都添加完毕后,我想显示一条消息,让用户知道博客已保存并重置表单。
问题是回调函数(cbAddBlog)是在$.when..中的代码之后执行的
当您定义了回调函数时,$.when 是否与 JSONP 一起使用?还是我的代码有其他问题?我是否需要在回调函数中自己实现 Deferred 才能使其工作?
var errorState = false,
contributorId = '23',
addBlogCalls = [];
$("#btnAddBlog").click(function (e) {
$('#add_contributor section.blog').each(function () { //call addBlog for each of the users blogs
addBlog(contributorId, $(this).attr('id'));
});
$.when.apply($, addBlogCalls).done(function () {
console.log("WHEN + errorState: " + errorState); //This is output to console BEFORE the line in the cbAddBlog callback function
});
e.preventDefault();
});
addBlog : function (contributorId, blogSection) {
//client side validation - following is excecuted if there are no errors
addBlogCalls.push(
$.ajax({
url : (apiRoot + "f=jsonp").trim(),
dataType : 'jsonp',
jsonp : false,
jsonpCallback : "cbAddBlog",
fail: function (e) {
console.log("error function");
console.log(e.message);
},
done: function (e) {
console.log("done function");
console.log(e.message);
}
})
);
console.log("Added to addBlogCalls array");
console.log(addBlogCalls);
}
cbAddBlog : function (data) {
console.log("cbAddBlog data.result: " + data.result); //Printed to console AFTER line from $.when ??
//code to check if there are any errors returned from server and display them to user
}
控制台输出:
Added to addBlogCalls array
[Object { readyState=1, setRequestHeader=function(), getAllResponseHeaders=function(), more...}]
Added to addBlogCalls array
[Object { readyState=1, setRequestHeader=function(), getAllResponseHeaders=function(), more...}, Object { readyState=1, setRequestHeader=function(), getAllResponseHeaders=function(), more...}]
WHEN + CD.config.errorState: false
cbAddBlog data.result: 1
cbAddBlog data.result: 1
我看到了同样的问题(回调在 $.when 之后执行,即使只有一个博客..
【问题讨论】:
标签: javascript jquery jsonp jquery-deferred .when