ajax调用后,无法在jquery中获取更新的cookie值

时间:2022-02-06 20:14:51

I have made a simple cart example in mvc. what I'm doing is , after clicking on Add to cart span , I'm calling a Controller Action method.

我在mvc中做了一个简单的cart示例。我所做的是,在单击Add to cart span之后,我调用一个控制器操作方法。

And then updating the cookie value with Total no of item in cart. but it give me initial value of cookie.

然后更新cookie值,购物车中的条目总数为no。它给出了cookie的初始值。

This is my Ajax Code to call Controller Action

这是调用Controller操作的Ajax代码

   $(document).delegate('.addCart','click', function () {
            var getId = parseInt($(this).attr('id').slice(3));
            $.ajax({
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                url: '/Comments/CartDetailsSetGet',
                data: { Id: getId },
                success: function (data) {
                    var count = parseInt(data);
                    if (isNaN(count)){
                        alert(data);
                    }else{
                        var getCookies=  @HttpContext.Current.Request.Cookies["CartCookie"].Value;
                        $('.cartNum').html(getCookies);
                    }
                },
                error: function (data) {
                    alert("Error In Adding Item To Cart");
                }
            });
        });

There is span > with class cartNum in which I'm showing Total no of item in cart .

有span >和类cartNum,其中我显示了cart中的所有项目。

addCart is span on which I'm Clicking to Add Item In Cart.

addCart是span,我单击它在Cart中添加项目。

This is my Action Method , which is My default Action

这是我的动作方法,这是我的默认动作

HttpCookie ck = new HttpCookie("CartCookie");
        public ActionResult Index()
        {
            if (Request.Cookies["CartCookie"] == null)
            {
                ck.Value = "0";
                Response.SetCookie(ck);
            }
            IList<Comment> commentList = db.Comments.ToList();
            return View(commentList);
        }

This Action Which is getting called On Ajax Request.

此操作将在Ajax请求时调用。

static List<int?> CartItemsId = new List<int?>();
        public string CartDetailsSetGet(int? Id)
        {
              if (CartItemsId.Contains(Id) != true)
                {
                    CartItemsId.Add(Id);
                    int getCount = CartItemsId.Count();
                    System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value = getCount.ToString();
                    ck.Expires = DateTime.Now.AddDays(-1);
                    var d = "";
                    if (System.Web.HttpContext.Current.Request.Cookies["CartCookie"] != null)
                    {
                        d = System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value;
                    }
                    return d.ToString();
                }
                else
                {
                    return "This Item Is Already In Cart";
                }            
        }

Here in d I'm getting updated cookie value but in Ajax Success , this line giving me Initial value, i.e 0.

在d中,我得到了更新的cookie值但在Ajax中,这一行给出了初始值I。e 0。

var getCookies= @HttpContext.Current.Request.Cookies["CartCookie"].Value;

var getCookies = @HttpContext.Current.Request.Cookies(“CartCookie”)value;

1 个解决方案

#1


2  

In you script, var getCookies = '@HttpContext.Current.Request.Cookies["CartCookie"].Value' is razor code and is parsed server side prior to be the browser. If you inspect the page source you will see that the value of getCookies is already set to "0".

在您的脚本中,var getCookies = '@HttpContext.Current.Request.Cookies["CartCookie"]。Value'是razor代码,在成为浏览器之前被解析为服务器端。如果您检查页面源代码,您将看到getcookie的值已经设置为“0”。

Rather than trying to set or update a cookie, return JSON data in the CartDetailsSetGet that contains the values you want to render, for example

与其尝试设置或更新cookie,不如返回CartDetailsSetGet中的JSON数据,其中包含您想要呈现的值

public JsonResult CartDetailsSetGet(int? Id)
{
  if (CartItemsId.Contains(Id) != true)
  {
    ....
    int getCount = CartItemsId.Count();
    var data = new { count = getCount , message = "some message" };
    return Json(data, JsonRequestBehavior.AllowGet);
  }
  {
    var data = new { count = null, message = "This Item Is Already In Cart" };
    return Json(data, JsonRequestBehavior.AllowGet);
  }
}

Script

脚本

$.ajax({
  ....
  success: function (data) {
    if (data.count) {
      $('.cartNum').html(data.count);
    } else {
      alert(data.message);
    }
  },
  ....

#1


2  

In you script, var getCookies = '@HttpContext.Current.Request.Cookies["CartCookie"].Value' is razor code and is parsed server side prior to be the browser. If you inspect the page source you will see that the value of getCookies is already set to "0".

在您的脚本中,var getCookies = '@HttpContext.Current.Request.Cookies["CartCookie"]。Value'是razor代码,在成为浏览器之前被解析为服务器端。如果您检查页面源代码,您将看到getcookie的值已经设置为“0”。

Rather than trying to set or update a cookie, return JSON data in the CartDetailsSetGet that contains the values you want to render, for example

与其尝试设置或更新cookie,不如返回CartDetailsSetGet中的JSON数据,其中包含您想要呈现的值

public JsonResult CartDetailsSetGet(int? Id)
{
  if (CartItemsId.Contains(Id) != true)
  {
    ....
    int getCount = CartItemsId.Count();
    var data = new { count = getCount , message = "some message" };
    return Json(data, JsonRequestBehavior.AllowGet);
  }
  {
    var data = new { count = null, message = "This Item Is Already In Cart" };
    return Json(data, JsonRequestBehavior.AllowGet);
  }
}

Script

脚本

$.ajax({
  ....
  success: function (data) {
    if (data.count) {
      $('.cartNum').html(data.count);
    } else {
      alert(data.message);
    }
  },
  ....