我有一个这样编码的按钮:
<asp:Button ID="save_all_filt" runat="server" Text="All data for filtered subjects"
ClientIDMode="Static" OnClientClick="a= saveAllFilt(); return a; "
OnClick="save_all_filt_Click" />
saveAllFilt是一个调用JQuery ajax调用的函数。像这样:
function saveAllFilt() {
jQuery.ajax({
async: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
type: "POST",
url: contentURL,
data: dataarray,
success: function (msg) {
// Some processing here. ONLY WHEN IT IS DONE, I NEED TO HAVE POSTBACK.
},
error: function (data) {
}
}); // end of ajax call.
}
我想要这样的事情:onClick应该只在ajax调用完成后进行。我怎么能做到呢?
您可以从按钮中删除OnClick
属性并在OnClientClick
属性中返回false,如:
<asp:Button ID="save_all_filt" runat="server" Text="All data for filtered subjects"
ClientIDMode="Static" OnClientClick="saveAllFilt(); return false;" />
并设置一个带有OnClick
属性的隐藏按钮,如:
<asp:Button ID="hdnButton" runat="server" Text="" Visible="False"
ClientIDMode="Static" OnClick="save_all_filt_Click" />
并在ajax
调用的成功方法中单击该按钮,如:
success: function (msg) {
// Some processing here. ONLY WHEN IT IS DONE, I NEED TO HAVE POSTBACK.
$('#hdnButton').click();
},
这很容易。在success函数中调用回发方法。查看下面的代码。
改变你的标记
<asp:Button ID="save_all_filt" runat="server" Text="All data for filtered subjects"
ClientIDMode="Static" OnClientClick="a=saveAllFilt(); return false;"
OnClick="save_all_filt_Click" />
修改Java脚本代码
function saveAllFilt() {
jQuery.ajax({
async: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
type: "POST",
url: contentURL,
data: dataarray,
success: function (msg) {
// Some processing here.Now do the post postback
<%=Page.ClientScript.GetPostBackEventReference(save_all_filt,"") %>
},
error: function (data) {
}
});
我觉得你的想法很奇怪。为什么要在回发之前调用ajax
你还差得远呢。
代替:
<asp:Button ID="save_all_filt" runat="server" Text="All data for filtered subjects" ClientIDMode="Static" OnClientClick="a= saveAllFilt(); return a; " OnClick="save_all_filt_Click" />
试题:
<asp:Button ID="save_all_filt" runat="server" Text="All data for filtered subjects" ClientIDMode="Static" OnClientClick="return saveAllFilt()" OnClick="save_all_filt_Click" />
不同的是,OnClientClick="a= saveAllFilt(); return a;"
只是OnClientClick="return saveAllFilt()"
如果return true在ajax成功函数中不起作用。在ajax成功函数中使用__postback函数
只有在ajax调用完成后才会提交回发。
在您的.ajax()
调用的success
属性的代码之后尝试return true
。优先级总是这样:
- 客户端 服务器端
只有当客户端返回true
时,服务器才会启动点击。
function saveAllFilt() {
jQuery.ajax({
async: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
type: "POST",
url: contentURL,
data: dataarray,
success: function (msg) {
// Some processing here. ONLY WHEN IT IS DONE, I NEED TO HAVE POSTBACK.
return true;
},
error: function (data) {
return false;
}
});
}
此外,删除onclick
属性-在HTML中一个非性能属性(在我看来),并使用jquery的on()
.
在函数调用中,
OnClientClick="return saveAllFilt()";
在Ajax, 如果ajax调用成功返回true,其他情况返回false。