从 .ajax 返回时突出显示 msg 并将其附加到元素

Highlight and append msg to element on return from .ajax

提问人:Scott Thompson 提问时间:6/16/2021 最后编辑:a.akScott Thompson 更新时间:6/17/2021 访问量:134

问:

ajax 成功返回后,返回数据包含状态。如果 status 为 false(不是 ajax fail),则返回数据包含元素名称数组和关联的错误消息。目标是通过在元素和突出显示后附加 msg 来复制 .validate() 错误功能。

HTML 表单:

<form class="form-horizontal" id="chngPwdForm" action="changepwd.php" method="post">
.
. various HTML....
.
             <div class="form-group">
                <div class="alert alert-div font-weight-bold" id="errorTxt" role="alert" style="display:none;"> </div>
                <label for="crntPwd">Existing Password:</label>
                <div class="input-group-prepend">
                  <span class="input-group-text"><i class="fa fa-key fa-fw"></i></span>
                  <input type="password" class="form-control" id="crntPwd" name="crntPwd" required>
                </div>
             </div>
.
. more HTML follows
.

JQUERY:

.
.yada, yada, yada
.
    $("#chngPwdForm").submit(function(event){
    event.preventDefault();
    if ($("#chngPwdForm").valid() ) {
       $('#chngPwdForm div[id="errorTxt"]').hide();
       Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed.  Click on Login to continue.");   
       var formURL = $("#chngPwdForm").attr('action');
       $.ajax({
          url: formURL,
          type: 'POST',
          data: $(this).serialize(),
          dataType: 'JSON'
       })
       .done (function(data, textStatus, jqXHR) {
           if (!data.status) {
              var Msg = "Password Not Changed.  Password Change Failed.";
              var element;
              var errorObj = new Error("");
              $.each(data.Msg, function(elemName, errMsg) {
                  element = $("#chngPwdForm").filter("#" + elemName);
                  errorObj.message = errMsg;
                  $(element).closest(".form-group").addClass("has-error");
                  errorObj.insertAfter(element);
              });
           }
           $('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
       })
       .fail (function(response){ 
           var Msg = "chngPwd call failed. errorThrown: " + response;
           var obj = JSON.stringify(response);    
          alert("obj is: " + obj);
          $('#chngPwdForm div[id="errorTxt"]').text(Msg);
        })
      }
      else {
        $('#chngPwdForm div[id="errorTxt"]').text('Please Correct errors').show();
      }
      return false;

来自 changepwd.php 的 JSON 响应:

{\"status\":false,\"Msg\":{\"crntPwd\":\"Current Password may only contain a-z, A-Z, 0-9, ! or @\"}

JS 错误

“TypeError: errorObj.insertAfter is not a function” 被抛出
“errorObj.insertAfter(element);”

JavaScript jQuery ajax 错误处理 亮点

评论


答:

0赞 Scott Thompson 6/17/2021 #1

实施的解决方案:

JQuery:

// New Code has leading and trailing *
$("#chngPwdForm").submit(function(event){
     *$(".chngPwderr").removeClass("error").text('');* //used to remove old messages
     event.preventDefault();
     if ($("#chngPwdForm").valid() ) {
       $('#chngPwdForm div[id="errorTxt"]').hide();
       Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed.  Click on Login to continue.");   
       var formURL = $(this).attr('action');
       $.ajax({
          url: formURL,
          type: 'POST',
          data: $(this).serialize(),
          dataType: 'JSON'
       })
       .done (function(data, textStatus, jqXHR) {
           if (!data.status) {
              var Msg = "Password Not Changed.  Password Change Failed.";
              var focusSet = false;
              $.each(data.Msg, function(elemName, errMsg) {
              *$("#" + elemName).attr("type", "text");
               if (!$("#" + elemName).parent().hasClass("error")) {
                    $("#" + elemName).parent().append('<div class="chngPwderr error">' + errMsg + '</div>'); 
                  }  
                  if (!focusSet) {
                     $("#" + elemName).focus();
                    focusSet = true;
                  }*
              });
           }
           $('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
       })