JavaScript url 变量

发布于 2024-12-11 05:03:24 字数 219 浏览 0 评论 0原文

<script type="text/javascript" src="http://doamin.com/js/whatever.js?ref=images"></script>

注意到网址末尾的 ref=images 。我的问题是,如何从 url 获取 ref 变量并在同一个 js 文件中使用它。

I have

<script type="text/javascript" src="http://doamin.com/js/whatever.js?ref=images"></script>

Note the ref=images at the end of the url. My questions is, how do i get the ref variable from the url and use it inside this same js file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

極樂鬼 2024-12-18 05:03:24

简化 mrtsherman 的想法,只需找到具有正确 src 的脚本(在 whatever.js 中):

var whatever = $('script[src*=http://domain.com/js/whatever.js]')

if (whatever.length){
    var ref = whatever.attr('src').match(/\?ref=(.*)/)
    if (ref && ref[1]){
        ref = ref[1] // ref == 'images'
    }
}

更新: 因为您只想输出一些内容从 PHP 并在脚本中使用它,您有一个更好的选择:

<script id="whatever" src="http://domain.com/whatever.js" data-ref="images"></script>

然后从您的脚本(假设 jQuery >= 1.4):

var ref = $('#whatever').data('ref') // "images"

这是在客户端脚本中从服务器端获取数据的推荐和标准方法。

请参阅 http://html5doctor.com/html5-custom-data-attributes/http://dev.w3.org/html5/spec/elements.html#embedding-custom-non-visible-data

Simplifying mrtsherman's idea, just find the script with the correct src (from within whatever.js):

var whatever = $('script[src*=http://domain.com/js/whatever.js]')

if (whatever.length){
    var ref = whatever.attr('src').match(/\?ref=(.*)/)
    if (ref && ref[1]){
        ref = ref[1] // ref == 'images'
    }
}

update: since you just want to output something from PHP and use it in your script, you have a much better option:

<script id="whatever" src="http://domain.com/whatever.js" data-ref="images"></script>

Then from your script (assuming jQuery >= 1.4):

var ref = $('#whatever').data('ref') // "images"

This is the recommended and standard way to get data from server-side in your client scripts.

See http://html5doctor.com/html5-custom-data-attributes/ and http://dev.w3.org/html5/spec/elements.html#embedding-custom-non-visible-data

浮萍、无处依 2024-12-18 05:03:24

如果 whatever.js 只是一个 js 文件,则不能。

如果只是一个请求uri并使用服务器端脚本输出javascript内容,则可以从get参数中获取该变量。

如果你想将变量传递给whatever.js,你可以在include whatever.js之前定义变量,然后在whatever.js中使用该变量。

<script type="text/javascript">
<!--// 
  ref = 'images';
//-->
</script>

If whatever.js is a just js file, you can't.

If it is just a request uri and using the server side script to output the javascript content, you can get the variable from the get parameter.

If you want to pass the variable to the whatever.js, you can just define the variable before include whatever.js and then use the variable in whatever.js.

<script type="text/javascript">
<!--// 
  ref = 'images';
//-->
</script>
场罚期间 2024-12-18 05:03:24

我不知道如何仅获取当前块脚本元素的 src 属性。但是您可以获取页面上的所有脚本,然后解析它们。

//untested
var scripts = $('script[src]');
//loop through scripts and somehow identify the one that is yours
for (var script in scripts) {
  if (myscript) {
    var refvalue = getRef($(script).attr('src'), 'ref');
  }
}

//gup the parameter
function getRef(url, name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

希望这足以继续下去

I don't know of a way to get the src attribute for only the current blocks script element. But you could get all scripts on the page and then parse them.

//untested
var scripts = $('script[src]');
//loop through scripts and somehow identify the one that is yours
for (var script in scripts) {
  if (myscript) {
    var refvalue = getRef($(script).attr('src'), 'ref');
  }
}

//gup the parameter
function getRef(url, name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

Hopefully this is enough to go on

恋你朝朝暮暮 2024-12-18 05:03:24

试试这个 http://jsfiddle.net/fnE6w/

$("script[src*='ref=']").each(function(){
    var src=$(this).attr("src");
    var start=src.indexOf("ref=");
    var end=-1;


    if(start>0)
        end = src.indexOf("&",start+4);
    if(end==-1) end=src.length-1;    
    alert(src.substring(start+4,end));

});

try this http://jsfiddle.net/fnE6w/

$("script[src*='ref=']").each(function(){
    var src=$(this).attr("src");
    var start=src.indexOf("ref=");
    var end=-1;


    if(start>0)
        end = src.indexOf("&",start+4);
    if(end==-1) end=src.length-1;    
    alert(src.substring(start+4,end));

});
七七 2024-12-18 05:03:24

我似乎记得有一种方法可以在某些浏览器中获取调用脚本标记,但我找不到它的参考。

下一个最好的事情是遵循这样的内容: http://snipplr.com/view/354/

您可以使用您喜欢的源搜索脚本标签,然后提取字符串。 小心!如果您根据用户输入设置此值,您的用户可能会注入扫描仪可能会误解的查询字符串,从而产生风险。为此,应使用与常规查询字符串相同的偏执 URL 解析方法。

I seem to remember there being a way to get the calling script tag in some browsers but I can't find reference to it.

The next best thing is to follow something like this: http://snipplr.com/view/354/

You could search for the script tag with a source you like and then extract the string. Be careful! If you set this value based on user input your user could inject a query string that your scanner could misinterpret, creating a risk. The same kind of paranoid URL parsing approach used for regular query string should be used for this.

荆棘i 2024-12-18 05:03:24

你的问题是,你无法从脚本的 URL 获取查询:

<script src="http://doamin.com/js/whatever.js?ref=images">
     //Want to get the query here, but you can't
</script>

你说:

我正在使用 php.ini。 ref 取决于生成的 php 变量。我想将该变量传递给 js 文件。服务器端对我来说没问题。我认为最好的方法是将其作为 url 变量放在 js 文件的末尾。但我不知道如何访问它。其他方法对我来说没问题

让我们回到你的目的,将 php 变量传递给脚本...为什么不将 php 变量传递给包含脚本的 php 页面呢?然后使用其他发帖者提供的脚本获取它。您的包含脚本的 PHP 页面的 URL:

http://domain.com/ThePHPPageContainingTheScript.php?ref=images

那么该页面包含脚本:

<script src="http://doamin.com/js/whatever.js">
     //Get the query from window.location, it's possible!
</script>

Your problem here is, you cannot get the query from the URL of the script:

<script src="http://doamin.com/js/whatever.js?ref=images">
     //Want to get the query here, but you can't
</script>

You said:

I'm using php. ref depends on the generated php variable. I want to pass that variable to the js file. Server side is ok with me. I thought the best way to do it is to put it as a url variable at the end of the js file. But i don't know how to access it. Other methods are ok with me

Let's go back to your purpose, to pass a php variable to the script... Why not pass the php variable to the php page containing the script? Then get it using scripts provided by other posters here. Your URL to PHP page containing the script:

http://domain.com/ThePHPPageContainingTheScript.php?ref=images

Then this page contains the script:

<script src="http://doamin.com/js/whatever.js">
     //Get the query from window.location, it's possible!
</script>
剑心龙吟 2024-12-18 05:03:24

以防万一它对搜索类似内容的人有用,这里是一个不使用 AJAX 向脚本发送大量数据的方法示例。

<script src="test.js" name="testjs">
{
  "here"    : "is",
  "another" : "way",
  "of"      : "passing",
  "larger"  : "amounts",
  "of"      : "data",
  "to"      : "a script"
}
</script>

然后在外部 test.js 脚本中,您只需要以下内容:

(function(){
  var script = document.scripts.namedItem('testjs'), obj, data;
  if ( script && (data = script.innerHTML) ) {
    if ( typeof JSON != 'undefined' ) {
      obj = JSON.parse(data);
    }
    else if ( typeof jQuery != 'undefined' ){
      obj = jQuery.parseJSON(data);
    }
    /// obj now contains the object representation of your data
    alert(obj);
  }
})();

Just in case it is useful to anyone out there searching for something similar to this, here is an example of one way to send larger amounts of data to a script without the use of AJAX.

<script src="test.js" name="testjs">
{
  "here"    : "is",
  "another" : "way",
  "of"      : "passing",
  "larger"  : "amounts",
  "of"      : "data",
  "to"      : "a script"
}
</script>

Then in your external test.js script you just need the following:

(function(){
  var script = document.scripts.namedItem('testjs'), obj, data;
  if ( script && (data = script.innerHTML) ) {
    if ( typeof JSON != 'undefined' ) {
      obj = JSON.parse(data);
    }
    else if ( typeof jQuery != 'undefined' ){
      obj = jQuery.parseJSON(data);
    }
    /// obj now contains the object representation of your data
    alert(obj);
  }
})();
秋意浓 2024-12-18 05:03:24

您将需要类似于以下的代码。这得到了 ? 之后的所有内容。并将其分成基本上键/对数组。

var GETDATA = new Array();

// Get the string that follows the "?" in the window's location.
var sGet = window.location.search;
if (sGet) // if has a value...
{
 // Drop the leading "?"
 sGet = sGet.substr(1);

 // Generate a string array of the name value pairs.
 // Each array element will have the form "foo=bar"
 var sNVPairs = sGet.split("&");

 // Now, for each name-value pair, we need to extract
 // the name and value.
 for (var i = 0; i < sNVPairs.length; i++)
 {
  // So, sNVPairs[i] contains the current element...
  // Split it at the equals sign.
  var sNV = sNVPairs[i].split("=");

  // Assign the pair to the GETDATA array.
  var sName = sNV[0];
  var sValue = sNV[1];
  GETDATA[sName] = sValue;
 }
}

You will need code similar to the following. This gets everything after the ? and seperates it into basically key/pairs array.

var GETDATA = new Array();

// Get the string that follows the "?" in the window's location.
var sGet = window.location.search;
if (sGet) // if has a value...
{
 // Drop the leading "?"
 sGet = sGet.substr(1);

 // Generate a string array of the name value pairs.
 // Each array element will have the form "foo=bar"
 var sNVPairs = sGet.split("&");

 // Now, for each name-value pair, we need to extract
 // the name and value.
 for (var i = 0; i < sNVPairs.length; i++)
 {
  // So, sNVPairs[i] contains the current element...
  // Split it at the equals sign.
  var sNV = sNVPairs[i].split("=");

  // Assign the pair to the GETDATA array.
  var sName = sNV[0];
  var sValue = sNV[1];
  GETDATA[sName] = sValue;
 }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文