为prevent回发失败:参考isValid ="不确定" [英] To prevent postback failed: isValid="undefined"
问题描述
我有code至prevent回传,但失败了。基本上我有一个asp.net按钮。
I have the code to prevent postback but failed. Basically I have an asp.net button.
<asp:Button ID="btnSave" runat="server" Text="SaveChanges" OnClick="btnSave_Click"
CssClass="saveButton" ValidationGroup="answer" OnClientClick="return ValidateUserNameBeforeSubmitting();" />
和AJAX调用Web服务。
And ajax call web service.
function ValidateUserName() {
$.ajax({ type: "POST",
url: "../UserNameWebService.asmx/ValidateUserName",
data: "{'strUsername': '" +JSON.stringify( $("#<%=TextUserName.ClientID%>").val()) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
return data.d;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function ValidateUserNameBeforeSubmitting() {
var isValid = ValidateUserName();
return isValid;
}
Web服务将返回一个布尔值,它不会当我踏进code。 然而,当我走进的JavaScript code,我发现的isValid不是一个布尔值。它是不确定。 为什么呢?
The web service will return a boolean value and it does when I step into the code. However when I stepped into the javascript code, I found that "isValid" is not a boolean value. It is "undefined". Why?
感谢。
推荐答案
阿贾克斯是异步的。
VAR的isValid = ValidateUserName();
这行执行,但功能你调用没有返回(因此未定义
)
this line executes, but function you're calling has no return (hence undefined
)
如果您要访问从阿贾克斯返回一个变量,它需要在成功处理程序。
if you want to access a variable returned from ajax, it needs to be in the success handler.
function ValidateUserName() {
var returnValue;
$.ajax({ type: "POST",
...
async: false,
success: function (data) {
returnValue = data.d;
},
...
});
return returnValue;
}
这篇关于为prevent回发失败:参考isValid =&QUOT;不确定&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!