添加成功AJAX JSON $.post



我是JSON的新手,我正试图在我的JQuery AJAX帖子上添加一个成功的回调。成功只会简单地做一个location.reload()

现在我的post在更新我的DB方面工作得很好,但是重新加载位于我的AJAX方法之外,它发生在控制器实际处理数据之前的一瞬间,这意味着自动调用的重新加载发生在数据准备好之前。我希望重新加载等到AJAX完成它的工作。

$.post(
      '/Users/customCreate',
      {
           'name': name,
           'birthday': birthday,
           'bio': bio
      },
            function (data) { },
            "json"
       );
       location.reload(); //Want this in the success function
控制器

[HttpPost]
    public ActionResult customCreate(string name, string birthday, string bio)
    {
        DateTime dt;
        if (name == null || birthday == null || bio == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        try
        {
            dt = Convert.ToDateTime(birthday);
        }
        catch
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        if (ModelState.IsValid)
        {
            try
            {
                User user = new User();
                user.name = name;
                user.birthday = dt;
                user.bio = bio;  
                db.Users.Add(user);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (ArgumentOutOfRangeException)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
        }
        return RedirectToAction("Index");
    }

任何帮助将非常感激,因为我只使用JSON/AJAX的一小部分。

您可能希望在对.reload()的调用中包含forcedReload标志,以确保您不只是从数据库更新之前获取浏览器缓存的页面版本:

$.post('/Users/customCreate', {
    'name': name,
    'birthday': birthday,
    'bio': bio
}).done(function afterUserCreate(data) {
    location.reload(true);
});

(我还喜欢在$.post()之后链接.done()方法,并命名我的所有函数,以增加可读性和排除故障。)

这很简单:)

$.post(
      '/Users/customCreate',
      {
           'name': name,
           'birthday': birthday,
           'bio': bio
      },
            function (data) {location.reload();} //Now it's in the success function
       );

只需像这样在成功回调中重新加载:

$.post(
      '/Users/customCreate',
      {
           'name': name,
           'birthday': birthday,
           'bio': bio
      },
            function (data) { location.reload(); }
      });

您需要在Callback函数中编写后处理代码

$.post(
      '/Users/customCreate',
      {
           'name': name,
           'birthday': birthday,
           'bio': bio
      },
            function (data) { location.reload();}
       );

也可以使用$。Ajax函数,它完成了同样的事情。它更详细和可读。

$.ajax({
    type: "POST",
    url: '/Users/customCreate',
    data: {
        'name': name,
        'birthday': birthday,
        'bio': bio
    },
    success: function (data) {
        location.reload();
    },
});

最新更新