简体   繁体   中英

Pass variable value from one javascript to another

I have created Master Page EXAMPLE1.Master for my .net web application. Their I am storing value in JavaScript variable. I want to retrieve that variable in another JS File.

EXAMPLE1.Master:-

<script language="javascript" type="text/javascript">
        $(document).ready(function() {
            var pageAccess = '<%=Session["UserAccess"]%>';
            masterPageLoad();
        });
</script>

<script language="javascript" type="text/javascript" src="JS/pageActions.js">
</script>

pageAction.js

//Retrieve pageAccess variable here.

Definition of masterPageLoad(); is present in pageAction.js file

declare your pageAccess variable, before $(document).ready(function() {

like

var pageAccess = '<%=Session["UserAccess"]%>';
$(document).ready(function() {
   masterPageLoad();
});

Move your variable declaration outside the function

var pageAccess = '<%=Session["UserAccess"]%>';
$(document).ready(function() {
        masterPageLoad();
});

This variable should now be visible in any JS file.

It would be preferable if you could do something like this:

$(document).ready(function() {
    masterPageLoad('<%=Session["UserAccess"]%>');
});

And then update your pageActions.js accordingly:

function masterPageLoad(pageAccess) {
    ...
}

But if you need to work with an external variable, the reason it's currently not working is that it's defined within the scope of the DOMReady handler. You should either extract the variable declaration to be outside of the DOMReady handler, or you should create a global variable:

window.pageAccess = '<%=Session["UserAccess"]%>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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