如何向我的 jqgrid 添加取消按钮?

2022-01-19 00:00:00 jquery ajax jqgrid

我的网站上有一个 jqgrid(版本 3.5.3),它通过对 Web 服务的 ajax 调用获取结果.通常查询很复杂,加载结果需要几秒钟.在加载时,用户会看到一个框 [Loading...].

I've got a jqgrid (version 3.5.3) on my site which gets its results from an ajax call to a web service. Often the query is complicated and it takes a few seconds to load the result. While it is loading the user sees a box [Loading...].

如果用户意识到他们正在搜索错误的东西,客户端会要求在网格中添加一个取消按钮,这将:

In case the users realise they're searching for the wrong thing, the client has asked to add a cancel button to the grid, which would:

  1. 让网格忘记它刚刚请求的数据
  2. 保留先前搜索已加载的结果

似乎没有为此内置任何东西,所以我可能正在寻找一些技巧来实现这一点.

There doesn't seem to be anything built in for this, so I'm probably looking for a bit of a hack to achieve this.

有什么想法吗?

推荐答案

这是我们的解决方案,与 Oleg 的非常相似,主要区别在于我们跟踪 XHR 列表以确保清理所有请求

Here's our solution, which is very similar to Oleg's, the main difference is that we keep track of a list of XHRs to make sure we clean all requests up

var handlerUrl = '';

jQuery(document).ready(function() {
    var xhrList = [];

    var beforeSendHandler = function() {

        var cancelPendingRequests = function() {
            jQuery.each(xhrList, function() { this.abort(); });
            xhrList = [];
            return false;
        };

        var hideLoadingUI = function() {
            $(this).hide();
            $("#load_list").hide();
        };

        cancelPendingRequests();

        $("#load_list").show();

// some faffing around to ensure we only show one cancel button at a time
        if (jQuery("#cancelrequest").length == 0) {
            jQuery(".ui-jqgrid-titlebar").append(jQuery("<button   id='cancelrequest'>Cancel</button>").click(cancelPendingRequests).click(hideLoadingUI));
        } else {
            jQuery("#cancelrequest").show();
        };  
    }


    jQuery("#list").jqGrid({
        datatype: function(postdata) {

            GetSearchCriteria(); //needed for the grid's filtering

            var xhr = $.ajax({
                //we override the beforeSend so we can get at the XHRs, but this means we have to implement the default behaviour, like showing the loading message ourselves
                beforeSend: beforeSendHandler,
                dataType: "xml",
                data: postdata,
                success: function(xmlDoc) {
                    //
                    jQuery("#cancelrequest").hide();
                    $("#load_list").hide();
                    jQuery("#list")[0].addXmlData(xmlDoc);
                    xhrList = [];
                }

...

相关文章