简单问题真的。我有一个接受传递参数的JS函数。如果传递的值为NULL的可能性我想要它的陷阱,但我有限的JS经验导致我没有正确的语法。这里是。我需要做些什么来改变语法?显然还有更多的功能,但是当我没有捕获NULL时,其余的工作正常。错误的语法在最后一行,我知道它与使用保留字有关,但我不知道如何使其工作。
<script type="text/javascript">
//Pass UserName from text box on form to Ajax call
function CheckUserName(UserName_element) {
var UserName = try { UserName_element.value; } catch (e) { };
对于那些问你:这是一个vbscript Sub里面的js函数(不幸的是整个网站是用经典的asp编写的)
Sub UserNameValidation_Entry()
%>
<div id="username_validation" style="width:15px;position:relative;float:right;">
<img id="valid_UserName_image" src="<%=UrlForAsset("/images/tick.png")%>" border="0" style="display:none;" alt="User Name is Available."
title="User Name is Avaliable." />
<img id="invalid_UserName_image" src="<%=UrlForAsset("/images/icon_delete_x_sm.png")%>" border="0" style="display:none;" alt="User Name Already Exists."
title="User Name Already Exists." />
</div>
<script type="text/javascript">
//Pass UserName from text box on form to Ajax call
function CheckUserName(UserName_element) {
var UserName = UserName_element.value;
var UserName = try { UserName_element.value; } catch (e) { };
$j.ajax({
data: { action: 'CheckUserName', p_UserName: UserName },
type: 'GET',
url: 'page_logic/_check_username_ajax.asp',
success: function (result) {
//If user exists return X out, if not return green checkmark
if (result == "True") {
try { valid_UserName_image.style.display = "none"; } catch (e) { };
try { invalid_UserName_image.style.display = "inline"; } catch (e) { };
}
else {
try { valid_UserName_image.style.display = "inline"; } catch (e) { };
try { invalid_UserName_image.style.display = "none"; } catch (e) { };
}
}
}
);
//return false;
}
</script>
从这里打电话。
<tr class="required_field">
<td class="empty"></td>
<td><b>Username:</b></td>
<td class="label_value_separator"></td>
<td>
<input type='text' name="username" size="24" maxlength="50" value="<%=Session("s_username") %>" onblur="CheckUserName(this);">
<% Call UserNameValidation_Entry() %>
</tr>
答案 0 :(得分:2)
正如minitech所暗示的,你可能不需要尝试/捕捉这种情况。在尝试访问可能是"undefined"
的对象属性时,或者当您尝试解析可能无效的JSON时,这只是一个问题。
仅仅
就足够了if ( username !== null ) {
// Send AJAX request
} else {
// Send error to UI
}
还有许多其他类似JavaScript的检测模式in this answer。