您可以将URL参数传递给Javascript文件吗? [英] Can you pass URL parameters to a Javascript file?

查看:125
本文介绍了您可以将URL参数传递给Javascript文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<script src="myscript.js?someParameter=123"></script>

myscript.js内部,是否有任何方法可以将someParameter设置为123?还是使用服务器端脚本生成其中包含参数的javascript文件的唯一方法?

From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use server side scripts that generate the javascript file with the parameters in it?

推荐答案

好吧,您可以从window.location.href获取URL参数.顾名思义,它指的是当前窗口. <script>标记的作用是将链接的文件嵌入到当前文档中,从而嵌入到同一窗口中.如果从链接的JavaScript文件中解析window.location.href,则只能从嵌入文档中获取URL.

Well, you get URL parameters from window.location.href. As the name says, it refers to the current window. What the <script> tag does it to embed the linked file into the current document, thus into the same window. If you parsed window.location.href from the linked JavaScript file, you'd only get the URL from the embedding document.

有两种方法可以将参数传递到另一个JavaScript文件:

There are two ways to pass parameters to another JavaScript file:

  1. 按照@Dave Newton的建议,只需声明一个变量,然后像您一样嵌入JS文件(当然没有参数,因为它们没有效果).
  2. 创建一个iframe,将所需参数传递到iframe的网址,然后将JavaScript文件嵌入到iframe中. iframe将创建一个新的window实例.
  1. As @Dave Newton suggested, just declare a variable, then embed the JS file like you did (without the parameters of course, because they have no effect).
  2. Create an iframe, pass the parameters you want to the URL of the iframe, then embed the JavaScript file inside the iframe. An iframe will create a new window instance.

这篇关于您可以将URL参数传递给Javascript文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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