Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - How do I add a cancel button to my jqgrid?

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. make the grid forget about the data it's just requested
  2. retain the results already loaded from the previous search

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.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general $.ajax request returns XMLHttpRequest object having abort method. So if the corresponding call of the $.ajax would be have the form

var lastXhr = $.ajax ({
    // parameters
    success:function(data,st) {
       // do something
       lastXhr = null;
    },
    error:function(xhr,st,err){
        // do something
       lastXhr = null;
    }
});

and we would have access to the lastXhr valuable then we could be able to call lastXhr.abort(). I think that a new method like abortAjaxRequest in jqGrid can be the best solution.

Without changing of the current source code of jqGrid the solution could looks like following

var lastXhr;
var stopAjaxRequest(myGrid) {
    $('#cancel').attr('disabled', true);  // disable "Cancel" button
    lastXhr = null;
    myGrid[0].endReq();
};
var grid = $("#list");
grid.jqGrid ({
    // all standard options
    loadComplete() {
        stopAjaxRequest(grid);
    },
    loadError() {
        stopAjaxRequest(grid);
    },
    loadBeforeSend (xhr) {
        l$('#cancel').attr('disabled', false); // enable "Cancel" button
        lastXhr = xhr;
    }
});

$("#cancel").click(function() {
    if (lastXhr) {
        lastXhr.abort();
    }
});

In the code I suppose, that we have a "Cancel" button with the id="cancel" outside of jqGrid. I should mention, that I don't yet tested the code above, but I hope it should work.

You should understand, of cause, that the code above aborts only the waiting of the browser on the client side and the process on the server will be continued. If your server will be implement the server side aborting, then the code above will be not needed and you will be able to call this server aborting method directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...