真的很简单。我有一个接受传递参数的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>

最佳答案

就像微型技术所暗示的那样,您可能无需尝试/捕获这种情况。仅当尝试访问可能为"undefined"的对象属性时,或者当您尝试解析可能无效的JSON时,这才是真正的问题。

只需简单地

if ( username !== null ) {
  // Send AJAX request
} else {
  // Send error to UI
}


还有许多其他类似JavaScript的空值检测模式in this answer

关于javascript - 检查参数时出现陷阱错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28488169/

10-11 21:51