javascript jqgrid 如何显示服务器端消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14396701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:31:20  来源:igfitidea点击:

jqgrid how to show server side messages

javajavascriptservletsjqgridresponse

提问by Bhushan

I am using jqGridto show data in tabular format, using JSPand servlet.

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

EDIT

编辑

I want to show errors from server, when operations like insert, update, deleteare performed. (datatype: "xml")

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

JQGrid

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 Code

服务程序代码

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

for above example

对于上面的例子

  • after insertingrecord from jqgrid, then No message is shownin grid if record is inserted successfully
  • error Status: 'Unauthorized'. Error code: 401is shown if servlet fails to insert record in database.
  • 之后inserting从jqGrid的记录,然后No message is shown在网格如果记录inserted successfully
  • error Status: 'Unauthorized'. Error code: 401如果 servlet 无法在数据库中插入记录,则会显示。

My Question is that:

我的问题是:

  • after insertingrecord from jqgrid, if the record is inserted then how should i show message giving information to user that data is inserted.
  • and how should I give message to user that Error while inserting(which error codeshould i use for this?)
  • inserting从 jqgrid 记录后,如果插入了记录,那么我应该如何向用户显示插入数据的信息。
  • 以及我应该如何向用户发送消息Error while insertingerror code我应该为此使用哪个?)

Thanks in advance.....

提前致谢.....

采纳答案by Oleg

I suggested in the old answerand in another oneto use existing hidden row of grid form (tr.tinfo) to display information which is not error. Because the answers are not well known I repeat the same information here, but I'll try to explain all more detailed.

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

First of all it's important to understand which elements has the standard Edit/Add form. Using Developer Tools of IE or Chrome, Firebug or many other tool one can easy find out that the Add/Edit form created by jqGrid contains two hidden rows on top of the form:

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

enter image description here

在此处输入图片说明

The first row will be used per default as the place for error message. One can use errorTextFormatto customize the information a little.

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

If the server response contains error HTTP status code (>=400) then the callback errorTextFormatwill be called and you can use

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

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

or something like

或类似的东西

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

to display error message like

显示错误信息,如

enter image description here

在此处输入图片说明

In the same way one can use afterSubmitcallback to display status message after submitting of edited/added data if the server response contains successful HTTP status code. The implementation of afterSubmitcould be about the following

以同样的方式,afterSubmit如果服务器响应包含成功的HTTP 状态代码,则可以在提交编辑/添加数据后使用回调来显示状态消息。的实施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
}

The code will display the status message for 3 sec only abd then uses jQuery.slideUpanimation to hide it. It will look like

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

enter image description here

在此处输入图片说明

I hope it's what you need.

我希望这是你需要的。

回答by Mark

I have done somthing similar on an edit call to my server so I think this would work in a very similar manner to an add.

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

On the controller after an edit/delete/add call you would determine if there is a message to be passed to the user and if so pass it via the JSON (XML in your case) back to the grid.

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

Ex

前任

    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

In your jqGrid you would have your edit/delete/add function:

在您的 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){

So in the above example if the operation was a failure you could show a message with a success = falseor if the operation was completed but you wanted to pass some extra information to the user you could as well with sucess = true&& showMessage = true.

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

This is a JSON example of an edit but the concepts and logic should be the same for XML and an add/delete operation.

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