你需要使用两个调用- 1 get和1 post在ajax或你可以发送数据与成功/失败

Do you need to use two calls - 1 get and 1 post in ajax or can you send data back with the success / failure?

本文关键字:ajax 失败 成功 数据 post get 调用 两个      更新时间:2023-09-26

我有以下控制器方法:

    public JsonResult CreateGroup(String GroupName)
            {
                ApplicationUser user;
                var userName = User.Identity.Name;
                using (DAL.GDContext context = new DAL.GDContext())
                {
                    user = context.Users.FirstOrDefault(u => u.UserName == userName);                              
                    if (user != null)
                    {
                        var group = new Group();
                        group.GroupName = GroupName;
                        group.Members.Add(user);
                        context.Groups.Add(group);
                        context.SaveChanges();
                    }
                }
                string result = userName;
                return Json(result, JsonRequestBehavior.AllowGet);            
            }
with the following ajax call:
$(function () {
        $('#CreateGroup').on("click", function () {
            var groupName = $('#groupname').val();
            if (groupName != '') {
                $.ajax({
                    url: '@Url.Action("CreateGroup","AjaxMethods")',
                    type: "POST",
                    data: JSON.stringify({ 'GroupName': groupName }),
                    dataType: "json",
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        alert("success");
                        CreateGroup(data);
                    },
                    error: function () {
                        alert("An error has occured!!!");
                    }
                });
            }
        });

CreateGroup函数失败,提示"Uncaught ReferenceError: data is not defined"

我是否必须使用另一个Json请求类型的帖子来获取用户名?

您可以不使用JSON.stringify进行调用。此外,您的控制器方法有一个缓存属性,可以产生更多的控制。就我个人而言,我会使用控制器缓存控制。在返回数据之前,您可能会获得缓存版本的控制器调用。

 [OutputCache(NoStore = true, Duration = 0)]
 public ActionResult CreateGroup(string GroupName)

$.ajax({
    url: '@Url.Action("CreateGroup","AjaxMethods")',
    type: "POST",
    data: { 'GroupName': groupName },
    dataType: "json",
    traditional: true,    
    success: function (data, status, xhr ) {
        alert("success");
        CreateGroup(data);
    },
    error: function () {
        alert("An error has occured!!!");
    }
});