简体   繁体   English

在.js文件中调用URL参数

[英]Calling URL parameters within a .js file

I am calling a .js file within a HTML file. 我在HTML文件中调用.js文件。 On the URL to the .js file I want to include a parameter that will be accessable to the code INSIDE the .js file. 在.js文件的URL上,我想要包含一个参数,该参数可以访问.js文件中的代码。

For example: 例如:

I want to be able to pass the ID value to a function within the jquery_widget.js file, with the help of jQuery. 我希望能够在jQuery的帮助下将ID值传递给jquery_widget.js文件中的函数。 How is this done? 这是怎么做到的?

Thankful for all help! 感谢所有的帮助!

You can't do it like that: you have to declare the variable before loading the script. 你不能这样做:你必须在加载脚本之前声明变量。 Example: 例:

<script type="text/javascript">
    var foo= "bar";
</script>
<script type="text/javascript" href="path/to/js.js"></script>

in this way, the variable will be ready for your script. 通过这种方式,变量将为您的脚本做好准备。

Another solution is to use a php script, that can then use the GET variable. 另一种解决方案是使用php脚本,然后可以使用GET变量。 In that case, make sure you tell via a header() call that you are outputting javascript 在这种情况下,请确保通过header()调用告诉您正在输出javascript

<script type="text/javascript" src="ip.php"></script>

And the ip.php 和ip.php

<?
//"ip.php" example- display user IP address on any page
Header("content-type: application/x-javascript");
$serverIP=$_SERVER['REMOTE_ADDR'];
echo "document.write(\"Your IP address is: <b>" . $serverIP . "</b>\")";
?>

You use something like php 你使用像php这样的东西

your html file:
<script type="text/javascript" src="yourFile.php?var=123">  

yourFile.php:  
// <?php echo($_GET["var"]); ?>

Or, you could define a global variable and have the javascript access that variable. 或者,您可以定义一个全局变量并让javascript访问该变量。

Approach the problem differently: 以不同方式解决问题:

  1. Include your .js file 包括你的.js文件
  2. Call a function defined in your .js file with a parameter (ie your ID value) 使用参数 (即您的ID值)调用.js文件中定义的函数

The javascript file by itself is not aware of the URL it's being loaded from. javascript文件本身不知道从中加载的URL。

What you can do is assign an ID to the script tag you're including in the HTML page, and then grab the SRC attribute through jQuery. 你可以做的是为你在HTML页面中包含的script标记分配一个ID,然后通过jQuery获取SRC属性。 By parsing the URL value, you can extract the parameter. 通过解析URL值,您可以提取参数。

<script id='widgetJs' src='...'></script>

var url = $("#widgetJs").attr("src");
var q = url.split("?")[1];
if (q) {
    var params = q.split("&");
    etc. etc... 
    i'm not even going to explain further because there are better solutions.
}

A simpler solution is to declare a global variable in a separate script tag (namespace it to avoid conflicts) and then use it directly in your script. 一个更简单的解决方案是在单独的script标记中声明一个全局变量(命名空间以避免冲突),然后直接在脚本中使用它。

Or better yet, have an initialize(param) function in your script that you invoke from the HTML file (this saves you from polluting the global context with unnecessary variables). 或者更好的是,在脚本中有一个initialize(param)函数,您可以从HTML文件中调用(这样可以避免使用不必要的变量来污染全局上下文)。

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href
                     .indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

Source: http://snipplr.com/view.php?codeview&id=799 资料来源: http//snipplr.com/view.php?codeview&id = 799

HTML and javascript files are static resources and will be interpreted only by the client browser, so you can't pass any query params to these values and read them inside, What you can do is dynamically generate your javascript files with params at serverside and then include it as part of the page. HTML和javascript文件是静态资源,只能由客户端浏览器解释,所以你不能将任何查询参数传递给这些值并在里面读取它们,你可以做的是在服务器端用params动态生成你的javascript文件然后将其作为页面的一部分包含在内。 Or other simple way is write your js file as a php or jsp file and set the content type of the page to text/javascript and you can access all the params inside it 或者其他简单的方法是将您的js文件写为php或jsp文件,并将页面的内容类型设置为text/javascript然后您可以访问其中的所有参数

If you're trying to read parameters from the url, I've used: 如果你试图从网址读取参数,我用过:

function PageQuery(q) {
    if (q.length > 1) this.q = q.substring(1, q.length);
    else this.q = null;
    this.keyValuePairs = new Array();
    if (q) {
        for (var i = 0; i < this.q.split("&").length; i++) {
            this.keyValuePairs[i] = this.q.split("&")[i];
        }
    }
    this.getKeyValuePairs =  function() { return this.keyValuePairs; }
    this.getValue = function(s) {
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            if (this.keyValuePairs[j].split("=")[0] == s)
                return this.keyValuePairs[j].split("=")[1];
        }
        return false;
    }
    this.getParameters = function() {
        var a = new Array(this.getLength());
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            a[j] = this.keyValuePairs[j].split("=")[0];
        }
        return a;
    }
    this.getLength = function() { return this.keyValuePairs.length; }
}
function queryString(key) {
    var page = new PageQuery(window.location.search);
    return unescape(page.getValue(key));
}
function displayItem(key) {
    if (queryString(key) == 'false') {
        document.write("you didn't enter a ?name=value querystring item.");
    } else {
        document.write(queryString(key));
    }
}

cshtml file cshtml文件

<script src="@Url.Content("~/_scripts/CustomScripts/Coverage.js")" type="text/javascript"></script>   
@using (Html.BeginForm("Create", "Coverage")) {

}    
<script type="text/javascript">    getTypeIDByCategoryIdUrl = '@Url.Action("GetTypeIDByCategoryId")';  </script>

Coverage.js Coverage.js

var getTypeIDByCategoryIdUrl = ""; $(function () {
      $('#SeletedParrentIDTypeCode').change(function () {
      alert(getTypeIDByCategoryIdUrl); }

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

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