首页 > 解决方案 > 如何在javascript中将应用程序的值作为变量?

问题描述

我有一个计数器,每次页面加载时都会自行更新。我想将该计数器的值用作 javascript 中的变量,以便我可以使用它。我该怎么做呢?


    if (Application["counter"] == null)
        {
            Application["counter"] = 0;
        }
        if (Application["counter"] != null)
        {
            if (Request.Form["sub1"]==null)
            {
                Response.Write("<script>alert('You must Enter Number')</script>");
            }
            if (Request.Form["sub1"] != null)
            {
                Application["counter"] =(int)Application["counter"]+ 1;
                Response.Write(Application["counter"]);
            }
        }

这是cs页面中计数器的代码。每当我编写 Javascript 并尝试将其保存为变量时,它都会给我一个错误:错误 16 只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句。

var y=<%Application["counter"];>%;

标签: javascriptasp.net

解决方案


对于服务器端代码,您可以像下面这样使用它。只是一个建议。对于前端,你有错别字。

// Server side code - Correct usage

if (Application["counter"] == null) {
  Application["counter"] = 0;
}

// there's no need to check Application["counter"] after the code above

if (Request.Form["sub1"] == null)
{
  Response.Write("<script>alert('You must Enter Number')</script>");
}
// also, you can use else in here instead of another if, because there isn't any other condition.
else { 
  Application["counter"] = (int)Application["counter"] + 1;
  Response.Write(Application["counter"]);
}

// JS Code

var y = <%= Application["counter"] %>;

推荐阅读