简体   繁体   中英

jQuery Ajax Success nor Fail methods hit

I've got the following code below which is supposed to make a call to the controller when a link is clicked. The controller is getting called successfully, but the only method on the javascript side that is hit is always which displays a pop up stating "undefined".

Adding Method to Link

$('.retrieveTeam').click(function () {
        _getData($(this).data("teamkey"));
    });

jQuery AJAX Call

function _getData(postdata) {
    var request = $.ajax({
        url: 'RetrieveTeam',
        type: 'POST',
        data: JSON.stringify({ TeamKey: "331.l.542488.t.1" }),
        datatype: JSON,
        contentType: "application/json"
    });
    request.success = function (result) {
        alert(result);
    }
    request.error = function (result, xh) {
        alert("error");
    }
    request.fail = function () {
        alert("failure");
    }
    request.always = function (result) {
        alert(result);
    }
}

Controller

    [HttpPost]
    public JsonResult RetrieveTeam(string TeamKey)
    {
        List<Team> objTeams = (List<Team>)Session["Teams"];

        Team objTeam = objTeams.Where(x => x.TeamKey == TeamKey).FirstOrDefault();

        objTeam.AddPlayer(new FootballPlayer(new Position("QB", "QB", "QB"), "Brett Favre", "QB"));

        return Json(objTeam);
    }

You're using jQuery 2.1.1. Reading the manual page for $.ajax we can see that:

The jqXHR.success() , jqXHR.error() , and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done() , jqXHR.fail() , and jqXHR.always() instead.

In your code,

request.success = ...

should be replaced with

request.done(...)

and .fail = with .error() as well. Also, fix your dataType.
All together this brings us to:

function _getData(postdata) {
    $.ajax({
        url: 'RetrieveTeam',
        type: 'POST',
        data: JSON.stringify({ TeamKey: "331.l.542488.t.1" }),
        datatype: "json",
        contentType: "application/json"
    }).done(function (foo) {

    }).fail(function (foo) {

    }).always(function (foo) {

    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM