是否可以将GET或POST变量传递给外部javascript [英] Is it possible to pass GET or POST variable to external javascript

查看:82
本文介绍了是否可以将GET或POST变量传递给外部javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将任何变量传递给外部 java脚本文件

I am wondering whether is it possible to pass any variable to external java-script file

例如

我有这个

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

我想知道是否可以传递参数该脚本文件,如果是这样,我如何在外部文件中读取它?这样的事情可能是:???

I'd like to know if it's possible to pass an argument to that script file, and if so, how do I read it in the external file? Something like this perhaps:???

<script type="text/javascript" src="myscript.js?id=123"></script> 

谢谢

推荐答案

单独使用javascript,你可以这样做:

Using javascript alone, you can do it this way:

<script type="text/javascript">
function $_GET(q,s) { 
    s = s ? s : window.location.search; 
    var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');

    return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;

}  </script>

然后以这种方式使用javascript函数:

And then use the javascript function this way:

// this code would print "hello world" if it was at http://localhost/index.php?var1=hello&var2=world
var var1 = $_GET('var1');
var var2 = $_GET('var2');
document.write(var1 + " " + var2);

要从javascript的src标签获取所需的参数,你可以这样做:

To get the parameter needed from the src tag of the javascript you can do something like this:

// get the src parameter and split it down to the search query string
var src = document.getElementById('example').src;
params = src.split('?');
var var1 = $_GET('var1','?'+params[1]);

归功于Josh Fraser,我从这个答案中解释了这个答案。
http://www.onlineaspect。 com / 2009/06 / 10 / reading-get-variables-with-javascript /

Credit to Josh Fraser, from whom I paraphrased this answer. http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/

这篇关于是否可以将GET或POST变量传递给外部javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆