【问题标题】:jqgrid how to show server side messagesjqgrid如何显示服务器端消息
【发布时间】:2013-01-02 00:46:23
【问题描述】:

我使用jqGrid 以表格格式显示数据,使用JSPservlet

编辑

当执行insert, update, delete 之类的操作时,我想显示来自服务器的错误。 (datatype: "xml")

JQGrid

jQuery("#list10_d").jqGrid({
                height:250,
                width:600,
                url:'Assignment?action=Assign',
                datatype: "xml",
                colNames:['Sr. No.','PID',  'DATE',  'EMPID'],
                colModel:[{name:'srNo',index:'srNo', width:30,sortable:false},
                           {name:'PID',index:'PID',width:0, sortable:true,editable:false},
                           {name:'DATE',index:'DATE', width:75,sortable:true,editable:true,editoptions: { dataInit: function(el) { setTimeout(function() { $(el).datepicker({dateFormat:"dd-M-yy",showButtonPanel: true,changeYear: true,changeMonth: true}).attr('readonly','readonly'); }, 200); }}},
                           {name:'EMPID',index:'EMPID', width:150,sortable:true,editable:true}
                           ],
                rowNum:10,
                rowList:[10,20,50,100],
                pager: '#pager10_d',
                sortname: 'PID',
                viewrecords: true,
                sortorder: "asc",

                    },
                multiselect: true,
                editurl: "Assignment?action=Edit",
                caption:"Assignment"
            } ).navGrid('#pager10_d',{edit:false,add:true,del:false,addtext:'Assign '},
                    {},
                    {modal:true,jqModal: false,closeOnEscape:true,savekey: [true,13],closeOnEscape:true, recreateForm: true,width:500,mtype:'POST', url: 'Assignment',editData:{action: 'Assign',PID: function () {return PID;}}, 
                afterSubmit: function (response) {
                        alert('After Submit \n' +'statusText: '+ response.statusText);
                        var myInfo = '<div class="ui-state-highlight ui-corner-all">'+
                                     '<span class="ui-icon ui-icon-info" ' +
                                         'style="float: left; margin-right: .3em;"></span>' +
                                     response.statusText + 'Inserted'+
                                     '</div>',
                             $infoTr = $("#TblGrid_" + $.jgrid.jqID(this.id) + ">tbody>tr.tinfo"),
                            $infoTd = $infoTr.children("td.topinfo"); 
                        $infoTd.html(myInfo);
                        $infoTr.show();

                        // display status message to 3 sec only
                        setTimeout(function () {
                            $infoTr.slideUp("slow");
                        }, 5000);

                        return [true, "", ""]; // response should be interpreted as successful
                    },
                    errorTextFormat: function (response) {
                    alert('Error Text Format: \n' +'statusText: '+ response.statusText);

                        return '<span class="ui-icon ui-icon-alert" ' +
                                     'style="float:left; margin-right:.3em;"></span>' +
                                    response.statusText;},
                    {closeOnEscape:true, recreateForm: true,mtype: 'POST',url: 'Assignment',delData: {action: 'Delete',PID: function () {return PID;}}},
                    {}) ;

Servlet 代码

if(request.getParameter("action").equalsIgnoreCase("Assign"))
        {
            PID = request.getParameter("PID");
            String DATE= request.getParameter("DATE");
            String EMPID= request.getParameter("EMPID");

            String query = "insert into ASSIGN(PID,DATE,EMPID) values('"+ PID +"','"+ DATE +"','"+ EMPID"')";
            boolean b = insert.InsertData(query);
            if(b)
            {
                System.out.println("New record added successfully! : "+query);
                response.setContentType("text/xml");
                response.setCharacterEncoding("UTF-8");

                //response.sendError(200, "success");
                response.setStatus(200, "Inserted successfully");

            }
            else
            {
                System.out.println("Failed to add Record! : "+query);
                response.setContentType("text/xml");
                response.setCharacterEncoding("UTF-8");

                //response.sendError(399, "not Inserted successfully");   
                response.setStatus(404, "Error while inserting");   
            }           
        }//INSERT

上面的例子

  • 在来自 jqgrid 的 inserting 记录之后,然后在 No message is shown 中 如果记录为inserted successfully,则为网格
  • 如果 servlet 无法在数据库中插入记录,则会显示 error Status: 'Unauthorized'. Error code: 401

我的问题是:

  • 在来自 jqgrid 的inserting 记录之后,如果插入了记录,那么我应该如何向用户显示已插入数据的消息。
  • 我应该如何向用户发送Error while inserting 的消息(我应该使用哪个error code?)

提前谢谢.....

【问题讨论】:

    标签: java javascript servlets jqgrid response


    【解决方案1】:

    我在the old answeranother one 中建议使用现有的隐藏行网格形式(tr.tinfo)来显示没有错误的信息。因为答案并不为人所知,所以我在这里重复相同的信息,但我会尝试更详细地解释所有内容。

    首先,了解哪些元素具有标准的编辑/添加表单很重要。使用 IE 或 Chrome、Firebug 或许多其他工具的开发者工具可以很容易地发现 jqGrid 创建的添加/编辑表单包含在表单顶部隐藏的两个行

    默认情况下,第一行将用作错误消息的位置。可以使用errorTextFormat对信息进行一点自定义。

    如果服务器响应包含错误 HTTP 状态码 (>=400) 则回调 errorTextFormat 将被调用,您可以使用

    errorTextFormat: function (response) {
        return response.responseText;
    }
    

    或类似的东西

    errorTextFormat: function (response) {
        return '<span class="ui-icon ui-icon-alert" ' +
                     'style="float:left; margin-right:.3em;"></span>' +
                    response.responseText;
    }
    

    显示错误信息,如

    如果服务器响应包含成功的HTTP status code,则可以使用afterSubmit 回调在提交编辑/添加的数据后显示状态消息。 afterSubmit的实现大概如下

    afterSubmit: function (response) {
        var myInfo = '<div class="ui-state-highlight ui-corner-all">'+
                     '<span class="ui-icon ui-icon-info" ' +
                         'style="float: left; margin-right: .3em;"></span>' +
                     response.responseText +
                     '</div>',
            $infoTr = $("#TblGrid_" + $.jgrid.jqID(this.id) + ">tbody>tr.tinfo"),
            $infoTd = $infoTr.children("td.topinfo");
        $infoTd.html(myInfo);
        $infoTr.show();
    
        // display status message to 3 sec only
        setTimeout(function () {
            $infoTr.slideUp("slow");
        }, 3000);
    
        return [true, "", ""]; // response should be interpreted as successful
    }
    

    代码将仅显示 3 秒 abd 的状态消息,然后使用 jQuery.slideUp 动画将其隐藏。它看起来像

    我希望这是你需要的。

    【讨论】:

    • 我已经更新了我的问题,在实现您的代码后,现在消息显示在表单顶部,如图所示,但仅显示状态代码,如成功插入时只有 OK 是显示,当插入失败时,仅显示Not Found,但我无法显示 servlet 以表单形式发送的custom 消息。我在将错误从 servlet 发送到网格时是否出错?任何帮助将不胜感激...
    • @Bhushan:可能你使用了response.statusText 插入response.responseText。您能否将我的答案的当前代码与青年一号进行比较?
    • 我用过response.responseText,但没有显示任何内容
    • @Bhushan:您应该验证来自服务器的 HTTP 响应的信息。您可以使用 Fiddler、Firebug 或 IE 的开发者工具(按 F12 启动)或 Google Chrome 来检查完整的 HTTP 流量。您还可以在afterSubmit 内设置断点并检查response 的属性
    • @Bhushan:你修复了你的服务器代码吗?我不是Java开发人员,但我认为response.setStatus(如response.setStatus(200, "Inserted successfully");)的第二个参数的用法是错误的。 PrintWriter out = response.getWriter(); out.print("Inserted successfully"); out.flush(); 之类的代码似乎更正确。可能您应该使用response.setContentType("text/html; charset=UTF-8"); 而不是response.setContentType("text/xml")。见here
    【解决方案2】:

    我在对我的服务器的编辑调用中做了类似的事情,所以我认为这将以与添加非常相似的方式工作。

    在编辑/删除/添加调用后的控制器上,您将确定是否有要传递给用户的消息,如果是,则通过 JSON(在您的情况下为 XML)将其传递回网格。

        if (infoDialogTrigger) { 
           return Json(new { success = true, showMessage = true, message = "Updating your Inventory and we are displaying this info box" }); 
        }//if
        else { 
           return Json(new { success = true, showMessage = false, message = "" }); 
        }//else
    

    在您的 jqGrid 中,您将拥有编辑/删除/添加功能:

        function EditCollectionItem (rowid, grid){
            $(grid).jqGrid('editGridRow', rowid,
            {
                viewPagerButtons: false,
                editData: { },
                afterComplete: function (response) {
                    var DialogVars = $.parseJSON(response.responseText); //parse the string that was returned in responseText into an object
                    //if there was a failure with the update, or there was information to pass to the user
                    if (!DialogVars.success || DialogVars.showMessage) {
                        alert(DialogVars.message);
                    }
                } //afterComplete
            }); //$(grid).jqGrid('editGridRow
        }//function EditCollectionItem (rowid, grid){
    

    因此,在上面的示例中,如果操作失败,您可以使用success = false 显示一条消息,或者如果操作已完成但您想将一些额外信息传递给用户,您也可以使用sucess = true && showMessage = true

    这是一个 JSON 编辑示例,但概念和逻辑对于 XML 和添加/删除操作应该是相同的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 2016-05-11
      • 2011-10-21
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      相关资源
      最近更新 更多