简体   繁体   English

MVC视图中全局变量的范围

[英]Scope of global variables in MVC View

When I use global JavaScript variables in a View of MVC with Ajax, would the global variable be reset (re-declared) even though the page isn't refreshed? 当我在带有Ajax的MVC视图中使用全局JavaScript变量时,即使页面没有刷新,该全局变量也会被重置(重新声明)吗?

ie

<script>
var global = 0;
function func()
{
     global = 2;

     //passing global variable to a method "int square(int number)" in Home Controller
      $.ajax(
        {
            type: "POST",
            url: "../Home/square",
            data: { number : global },
            success: function (result)
            {
                alert(result);
            }
         };
}
</script>

Generally, what events would cause global variables in JavaScript to reset? 通常,什么事件会导致JavaScript中的全局变量重置?

Global variables in JavaScript will only be reinitialized in the event of a page refresh (ie F5 in your browser). 仅在刷新页面时(即浏览器中的F5),才会重新初始化JavaScript中的全局变量。

The page could be declared as a partial view and brought in via Ajax in which case the "Parent" page might not be refreshed, but each ajax request for the partial view would cause the JavaScript variables of that view to be re-initialized. 该页面可以声明为部分视图,并通过Ajax引入,在这种情况下,“父”页面可能不会刷新,但是对部分视图的每个ajax请求都会导致该视图的JavaScript变量被重新初始化。 Barring this scenario, your original statement about JavaScript variables and their lifetime would be correct. 除非出现这种情况,否则有关JavaScript变量及其生存期的原始声明将是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM