Domanda

I've inherited the following as part of a knockout.js grid.

It fills a grid with search results when you click the image input.

I would like to have it reload the page if the server times out (say 30 seconds) but I am very new to jQuery and am not sure where to start.

I can see a success in the code, and have found plenty of resources on timing things, but not sure what to test for or where to test it etc.

Please advise if you can and thank you in advance!

self.submitSearch = function () {
    $("#foundMembersTableParent").block({ message: '<img src="/Content/images/spinnerLarge.gif" /> Searching...' });
    self.selectedMembers.removeAll();
    fnOnSearch();
    $.ajax({
        type: 'POST',
        url: '/Members/MSearch',
        contentType: "application/json; charset=utf-8",
        data: self.getFormData(),
        success: function (data) {
            self.members($.map(data.searchResults, function (item) { return new Members(item) }));
            $("#foundMembersTableParent").unblock();
        },
        dataType: "json"
    });
}

self.getFormData = function () {
    var frmobj = $('#complexSearchForm').serializeObject();
    return JSON.stringify(frmobj);
 }
È stato utile?

Soluzione

Just add timeout and an error handler to your ajax request:

$.ajax({
    type: 'POST',
    url: '/Members/MSearch',
    contentType: "application/json; charset=utf-8",
    data: self.getFormData(),
    success: function (data) {
        self.members($.map(data.searchResults, function (item) { return new Members(item) }));
        $("#foundMembersTableParent").unblock();
    },
    dataType: "json",
    timeout: 30000,      // 30 seconds
    error: function(qXHR, textStatus, errorThrown) {
        if (textStatus === "timeout") {
            // request timed out, do whatever you need to do here
        }
        else {
            // some other error occurred
        }
    }
});

See the docs: https://api.jquery.com/jQuery.ajax/

As a wild guess, I think you are probably using this plugin:

http://malsup.com/jquery/block/#element

In which case, in your error handler, all you'd really need to do is:

$("#foundMembersTableParent").unblock();

To restore functionality to your grid. Of course, you might also want to bring up and error message somewhere so the user understands why the table didn't change.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top