Passing Querystring style parameters into Javascript file

后端 未结 2 2077
感动是毒
感动是毒 2020-12-21 15:39

Not sure if this is possible or even if I should do it, but I think it\'s quite interesting.

I have a javascript file which I\'m referencing in a flat HTML page. I\

相关标签:
2条回答
  • 2020-12-21 15:49

    This is a variation on Matt's answer. I have a similar case where I need a jQuery file to use a value that is generated in the HTML (by Razor in this case). I write the value to a meta tag, generated as it is from the controller:

    <meta name="sessionId" content="@ViewBag.SessionId">
    

    and then read it in the jQuery file:

    var sessionId = $("meta[name=sessionId]").attr("content");
    

    It's not quite the same as passing it in by querystring, but useful if that information is considered "meta-information" of the HTML page.

    0 讨论(0)
  • 2020-12-21 16:10

    I don't think that passing in variables via the src attribute is possible out of the box without some extra coding on your part (there is an article here if you are interested!). You could do the following though, which should provide the same functionality as you are looking for:

    Define your "config" variables in a single script block on your HTML page:

    <script type="text/javascript">
      var config1 = true;
    </script>
    

    Reference your external JS file in a second script block:

    <script src="/scripts/myJavascriptFile.js" type="text/javascript"></script>
    

    Add this code to your external JS file to reference the "local" variable in your HTML:

    var conf1 = window.config1;
    
    if (conf1) {
      // Do stuff
    }
    
    0 讨论(0)
提交回复
热议问题