在.js文件中调用URL参数

我在HTML文件中调用.js文件。 在.js文件的URL上,我想要包含一个参数,该参数可以访问.js文件中的代码。

例如:

我希望能够在jQuery的帮助下将ID值传递给jquery_widget.js文件中的函数。 这是怎么做到的?

感谢所有的帮助!

你不能这样做:你必须在加载脚本之前声明变量。 例:

  

通过这种方式,变量将为您的脚本做好准备。

另一种解决方案是使用php脚本,然后可以使用GET变量。 在这种情况下,请确保通过header()调用告诉您正在输出javascript

  

和ip.php

 " . $serverIP . "\")"; ?> 

你使用像php这样的东西

 your html file:  

或者,您可以定义一个全局变量并让javascript访问该变量。

以不同方式解决问题:

  1. 包括你的.js文件
  2. 使用参数 (即您的ID值)调用.js文件中定义的函数

javascript文件本身不知道从中加载的URL。

你可以做的是为你在HTML页面中包含的script标记分配一个ID,然后通过jQuery获取SRC属性。 通过解析URL值,您可以提取参数。

  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. } 

一个更简单的解决方案是在单独的script标记中声明一个全局变量(命名它以避免冲突),然后直接在脚本中使用它。

或者更好的是,在您的脚本中有一个initialize(param)函数,您可以从HTML文件中调用(这样可以避免使用不必要的变量来污染全局上下文)。

HTML和javascript文件是静态资源,只能由客户端浏览器解释,所以你不能将任何查询参数传递给这些值并在里面读取它们,你可以做的是在服务器端用params动态生成你的javascript文件然后将其作为页面的一部分包含在内。 或者其他简单的方法是将您的js文件写为php或jsp文件,并将页面的内容类型设置为text/javascript然后您可以访问其中的所有参数

cshtml文件

  @using (Html.BeginForm("Create", "Coverage")) { }  

Coverage.js

 var getTypeIDByCategoryIdUrl = ""; $(function () { $('#SeletedParrentIDTypeCode').change(function () { alert(getTypeIDByCategoryIdUrl); } 
 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; } 

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

如果你试图从url读取参数,我用过:

 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)); } }