【问题标题】:jQuery form submission with sucess and error message带有成功和错误消息的 jQuery 表单提交
【发布时间】:2011-04-12 18:27:54
【问题描述】:

我正在使用 jQuery 进行表单提交和验证,从服务器端我收到 JSON 格式的响应..

我在 jQuery 对话框中显示消息,但无法显示来自服务器的消息....

我的做法:

<script type="text/javascript">
//<![CDATA[
    $.validator.setDefaults({
    submitHandler: function() { 
        var spogName         = $("input#spogname").val();
        var spogDis            = $("input#spogdescription").val();
        var dataString         ='&spogName='+ spogName +'&spogDescription=' + spogDis;
        $.ajax({
            url: "/cpsb/spogMaster.do?method=addSpog",    
            type: "POST",        
            data: dataString,        
            cache: false,
            success: function() {  
                $("#dialog-message").dialog({
                    resizable:false,
                    height:180,
                    modal: true,
                    buttons: {
                        Ok: function() {
                            $(this).dialog('close');
                        }
                    }
                });

               },   

           error: function() {
           }                    
        });
    },
    highlight: function(input) {
        $(input).addClass("ui-state-highlight");
    },
    unhighlight: function(input) {
        $(input).removeClass("ui-state-highlight");
    }
});

$(document).ready(function() {
    navMenu();
    $("#spogForm").validate({
        rules: {
            spogname:{
            required: true
            }
        },
        messages: {
            spogname: "Please enter the Spog Name"
        }
    });

    $(":submit").button();
});
//]]>
</script>

我的标记:

<div id="dialog-message" title="Spog Message" style="display:none;">
    <p>
        <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
         Spog added successfully!
    </p>
</div>
<div id="header"><jsp:include  page="../menu_v1.jsp"/></div>
<div id="mainContent">
<div id="spog_form">
  <form class="cmxform" id="spogForm" method="post" action="/cpsb/spogMaster.do?method=addSpog">
    <fieldset class="ui-widget ui-widget-content ui-corner-all">
        <legend class="ui-widget ui-widget-header ui-corner-all">ADD SPOG</legend>
        <p>
            <label for="spogname">Spog Name (required)</label>
            <input id="spogname" name="spogName" class="required ui-widget-content" minlength="2" />
        </p>
        <p>
            <label for="spogdescription">Spog Description </label>
            <input id="spogdescription" name="spogDescription" class="spogD ui-widget-content" />
        </p>

        <p>
            <button class="submit" type="submit">Submit</button>
        </p>
    </fieldset>
</form>
</div>
</div>
</body>

如果数据库中存在spog,我得到的json字符串:

{"messageId":"errorMessage","message":"spog found with Name 10000 Description nuts"}

更新 1:

<script type="text/javascript">
//<![CDATA[
    $.validator.setDefaults({
    submitHandler: function() { 
        var spogName         = $("input#spogname").val();
        var spogDis            = $("input#spogdescription").val();
        $.ajax({
            url: "/cpsb/spogMaster.do?method=addSpog",    
            type: "POST",    
            datatype:'json',    
            data: {
                method:"addSpog",
                spogName:spogName,
                spogDescription:spogDis
            },    
            cache: false,
            success: function(data) {
              if ( data.messageId === 'errorMessage' ) {
                // server responded with an error, show the error placeholder
                // fill in the error message, and spawn the dialog
                $("#dialog-message")
                  .find('.success').hide().end()
                  .find('.error').show()
                    .find('.message').text( data.message ).end()
                    .end()
                  .dialog({
                    resizable:false,
                    height:180,
                    modal: true,
                    buttons: {
                      Ok: function() {
                        $(this).dialog('close');
                      }
                    }
                  });
              } else {
                // server liked it, show the success placeholder and spawn the dialog
                $("#dialog-message")
                  .find('.error').hide().end()
                  .find('.success').show().end()
                  .dialog({
                    resizable:false,
                    height:180,
                    modal: true,
                    buttons: {
                      Ok: function() {
                        $(this).dialog('close');
                      }
                    }
                  });
              }
            }
        });
    },
    highlight: function(input) {
        $(input).addClass("ui-state-highlight");
    },
    unhighlight: function(input) {
        $(input).removeClass("ui-state-highlight");
    }
});

$(document).ready(function() {
    navMenu();
    $("#spogForm").validate({
        rules: {
            spogname:{
            required: true
            }
        },
        messages: {
            spogname: "Please enter the Spog Name"
        }
    });


    $(":submit").button();
});
//]]>
</script>

标记:

<div id="dialog-message" title="Spog Message" style="display:none;">
    <p class="success">
        <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
         Spog added successfully!
    </p>
    <p class="error">
        An error occurred while adding spog: 
        <span class="message"></span>
    </p>
</div>

【问题讨论】:

  • 你服务器端的代码是什么?
  • 您的代码中有一个明显的错误:您使用 datatype 就像在 jqGrid 中一样。 jQuery.ajax 参数为dataType。此外,在error 句柄中至少包含alert("error!")
  • 我会建议你返回一些错误的 HTTP 状态代码以防出错(参见apl.jhu.edu/~hall/java/Servlet-Tutorial/…)。 HttpServletResponse 具有您可以使用的 setStatussendError 方法(请参阅 java2s.com/Code/JavaAPI/javax.servlet.http/…)。例如HttpServletResponse.SC_BAD_REQUEST 最好是 200(OK)。您还应该尝试在您的 servlet 中抛出异常并检查数据是如何进入errorajax 句柄的。您是否应该调用JSON.Parse 来解码错误响应。
  • @Oleg..problem 是它无法访问 if block 并直接转到 else block 和 ...并且在 $.ajax 文档中我可以使用 datatype:json ...problem访问来自服务器的 json 响应...

标签: jquery forms message submission


【解决方案1】:

在“成功”上面添加以下内容:datatype: "json",

然后将成功改为:

success: function(data) {  
    $("#dialog-message").append('<p>'+data.message+'</p>').dialog({
        resizable:false,
        height:180,
        modal: true,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
            }
        }
    });
},

基本上你需要;
a)告诉你的代码你的服务器将返回 JSON(因此它应该评估它)
b)用那个 JSON 做点什么——例如拉出消息并将其附加到您的对话框中

请理解以上代码只是一个建议,我没有测试过!

【讨论】:

  • 其实是个意外。我试图删除赞成票,但它却反对票。
  • @Sam 我投票给你+1 ...我使用@BBonified 方法并添加该json 数据类型,但仍然只能接收一条消息,当spog 已经存在时无法接收另一条消息存在于数据库中
  • @BBonifield - 我已经编辑了我的帖子。 @paul - 我们可以查看演示页面以便调试问题吗?目前我们都在盲目地工作!
  • @Sam 我的应用程序仍处于开发阶段,没有任何公共 URL....我尝试调试它并看到它没有转到 if 语句,而是直接转到 else 块并显示成功消息而不是显示错误消息....所以它没有执行 if ( data.messageId === 'errorMessage' )
【解决方案2】:

正如@Sam 所说,您需要调整成功回调,还需要稍微调整一下 HTML。

<div id="dialog-message" title="Spog Message" style="display:none;">
    <p class="success">
        <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
         Spog added successfully!
    </p>
    <p class="error">
        An error occurred while adding spog: 
        <span class="message">placeholder</span>
    </p>
</div>

然后JS改...

success: function(data) {
  if ( data.messageId && data.messageId === 'errorMessage' ) {
    // server responded with an error, show the error placeholder
    // fill in the error message, and spawn the dialog
    $("#dialog-message")
      .find('.success').hide().end()
      .find('.error').show()
        .find('.message').text( data.message ).end()
        .end()
      .dialog({
        resizable:false,
        height:180,
        modal: true,
        buttons: {
          Ok: function() {
            $(this).dialog('close');
          }
        }
      });
  } else {
    // server liked it, show the success placeholder and spawn the dialog
    $("#dialog-message")
      .find('.error').hide().end()
      .find('.success').show().end()
      .dialog({
        resizable:false,
        height:180,
        modal: true,
        buttons: {
          Ok: function() {
            $(this).dialog('close');
          }
        }
      });
  }
},

【讨论】:

  • 好吧,我尝试了你的建议,但它仍然显示 spog 添加成功,而不是显示服务器响应 {"messageId":"errorMessage","message":"spog found with Name 10000 Description toys"}
  • 您是否将“成功:函数(){”正确更改为“成功:函数(数据){”?假设您的服务器提供了正确的“application/json”内容类型标头并写出数据,它应该可以正常工作。
  • 是的,我改成了函数(数据)。请按照你上面的建议检查我更新的js
  • 您是否通过 console.log() 验证了“数据”实际上是正确的 JSON 返回对象?
  • 是的,我验证了 JSON 字符串,它是 {"messageId":"errorMessage","message":"spog found with Name 10000 Description toys"}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 2012-01-11
  • 2011-09-01
  • 2017-11-17
  • 1970-01-01
  • 2013-01-10
相关资源
最近更新 更多