سؤال

I'm using a formatter on one of my columns in jqGrid. The formatter uses some logic to decide what to display, and in some cases, it calls an ajax method. I've verified in Fiddler that the proper data comes back from my ajax calls. I've also verified in Chrome degbugging tools, that my variables are getting set properly. However, the sequence is all out of sorts, so the returned value in my column is "undefined". I can see in debugging tools' timeline that my getJSON calls are getting called after the jqgrid is already loaded.

I tried this first:

function myFormatter(cellvalue, options, rowObject) 
{
    if (rowObject[0] == something) {
        $.getJSON('@Url.Action("MyAction", "MyController"), function (myResult) {
            var myObject = myResult[0];
            return myObject.myID;
        });
    }
    else {
        return "";
    }
}

I also tried using an ajax call w/ async=false and I've tried different values for type and dataType, but the results are all the same:

function myFormatter(cellvalue, options, rowObject) 
{
    if (rowObject[0] == something) {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("MyAction", "MyController"),
            async: false,
            success: (function(result) {
                var myObject = myResult[0];
                return myObject.myID;
            })
        });        
    }
    else {
        return "";
    }
}
هل كانت مفيدة؟

المحلول

It seems like you should be able to get this to work by using a synchronous AJAX call and a closure:

function myFormatter(cellvalue, options, rowObject) 
{
    var value = "";

    if (rowObject[0] == something) {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("MyAction", "MyController"),
            async: false,
            success: (function(result) {
                var myObject = myResult[0];
                value = myObject.myID;
            })
        });        
    }

    return value;
}

In general it is bad practice to use synchronous AJAX calls though, because they can block the UI for an undetermined amount of time. This case could be especially bad if you have a lot of rows in your grid, because one AJAX call will be made per row.

If you can, a better approach might be to either retrieve the ID's ahead of time and cache them locally on the page, or just do the formatting server-side. As always, use your best judgement.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top