当使用 jQuery $.ajax 调用时,如果一切正常,从操作方法返回什么

本文关键字:操作方法 什么 返回 如果 jQuery ajax 调用 | 更新日期: 2023-09-27 18:32:50

这是我的代码:

    [HttpPost]
    public ActionResult VoteChampionStrongAgainst(string championStrong, string againstChampion)
    {
        int champStrongId = int.Parse(championStrong);
        int againstChampId = int.Parse(againstChampion);
        string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
        using (EfCounterPickRepository counterPickRepository = new EfCounterPickRepository())
        {
            var existingCounterPick = counterPickRepository.FindAll()
                                                           .SingleOrDefault(x => x.ChampionStrong == champStrongId && x.AgainstChampion == againstChampId);
            //Does this counterpick combination already exist?
            if (existingCounterPick != null)
            {
                //Has this user already voted?
                var existingVote = counterPickRepository.FindVoteForUser(ip, existingCounterPick.CounterPickVoteId);
                //He hasn't voted, add his vote history.
                if (existingVote == null)
                {
                    StrongCounterHistory history = new StrongCounterHistory();
                    history.IPAddress = ip;
                    history.VoteType = true;
                    history.StrongCounterPickVoteId = existingCounterPick.CounterPickVoteId;
                    counterPickRepository.AddStrongPickHistory(history);
                    counterPickRepository.SaveChanges();
                    //Add a total vote the pick.
                    existingCounterPick.TotalVotes++;
                    counterPickRepository.SaveChanges();
                }
                else
                {
                    //Will use this to display an error message.
                    //How to return an "error" that jquery understands?
                }
            }
            else //This combination doesn't exist. Create it.
            {
                //Create it....
                StrongCounterPickVote newCounterPick = new StrongCounterPickVote();
                newCounterPick.ChampionStrong = champStrongId;
                newCounterPick.AgainstChampion = againstChampId;
                newCounterPick.TotalVotes = 1;
                counterPickRepository.CreateNewCounterPick(newCounterPick);
                counterPickRepository.SaveChanges();
                //Assign a vote history for that user.
                StrongCounterHistory history = new StrongCounterHistory();
                history.IPAddress = ip;
                history.VoteType = true;
                history.StrongCounterPickVoteId = newCounterPick.CounterPickVoteId;
                counterPickRepository.AddStrongPickHistory(history);
                counterPickRepository.SaveChanges();
            }
            return View();
        }
    }

这是我的jQuery代码:

$(".pick .data .actions .btn-success").click(function () {
    var champStrongId = $(this).data("champstrongid");
    var againstChampId = $(this).data("againstchampid");
    $.ajax({
        type: 'POST',
        url: "/Counterpicks/VoteChampionStrongAgainst",
        data: { championStrong: champStrongId, againstChampion: againstChampId },
        success: function () {
            alert("Great success!");
        },
        error: function (e) {
            alert("Something bad happened!");
            console.log(e);
        }
    });
});

我需要从我的 ActionMethod 返回什么,以便代码执行success:如果一切顺利,或者如果出现问题error:(例如,他已经对这个特定的计数器选择进行了投票?

当使用 jQuery $.ajax 调用时,如果一切正常,从操作方法返回什么

Servlet 应该回答"200 OK"的 HTTP 响应。

不知道你的"View"api,但HttpServletResponse.setStatus(200)可以在Java端做。不要忘记,您可以在浏览器中手动请求 AJAX url 以查看它返回的内容。

以下是我会做的一些事情...

public JsonResult VoteChampionStrongAgainst(string championStrong, string againstChampion)    {
    var success = true;
    // Do all of your data stuff
    return Json(new { success = success, error = 'Some error message'});
}

JsonResult 是用于返回 Json 的特殊操作结果。它会自动为浏览器设置正确的标头。Json()将使用 ASP。NET 的内置序列化程序,用于序列化匿名对象以返回到客户端。

然后用你的jQuery代码...

$.ajax({
        type: 'POST',
        url: "/Counterpicks/VoteChampionStrongAgainst",
        data: { championStrong: champStrongId, againstChampion: againstChampId },
        success: function (json) {
            if (json.success) {
                alert("Great success!");
            }
            else if(json.error && json.error.length) {
                alert(json.error);
            }
        },
        // This error is only for responses with codes other than a 
        // 200 back from the server.
        error: function (e) {
            alert("Something bad happened!");
            console.log(e);
        }
    });

为了触发错误,您必须返回不同的响应代码,并Response.StatusCode = (int)HttpStatusCode.BadRequest;

如果您的服务器上有任何错误,您可以返回 500 内部服务器错误,

例如
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Response.ContentType = "text/plain";
return Json(new { "internal error message"});