【问题标题】:Read GET parameters using Javascript使用 Javascript 读取 GET 参数
【发布时间】:2018-01-20 09:22:15
【问题描述】:

我想在 HTML 文件中调用 Javascript,如下所示:

<body>
<script src="./sample.js?ts=123456789&id=31ade2"></script>
</body>

如何在sample.js 中使用tsid?这甚至可能吗?

我在 Google 上搜索,但我发现使用 location.href,它没有返回 tsid

(解释为什么window.location.href 不能解决这个问题。) 假设上面的脚本在example.com/index.html 中。 window.location.href in sample.js 返回 example.com/index.html 但不是 ./sample.js?ts=123456789&amp;id=31ade2

【问题讨论】:

  • 那些参数到服务器;除非您在那里做出规定以某种方式注入它们,否则脚本不会看到它们。但是context是什么,为什么你认为你需要这样做?
  • 你在使用节点吗?
  • @jonrsharpe 我认为将参数传递给sample.js 的最简单方法是使用变量。例如,我可以设置window._values = {'ts': '123456789', 'id': '31ade2'};sample.js 可以读取它。我只是认为使用 GET 参数更聪明。
  • @EdHeal 我从未研究过节点,所以不确定它可以做什么。这次我只在Nginx服务器中放了一个静态js文件。

标签: javascript html get


【解决方案1】:

sample.js 中,您需要获取对脚本元素本身的引用。简单的方法是阅读document.scripts collection:

const thisScript = document.scripts[document.scripts.length - 1]
const params = getParams(thisScript.src)

console.log(params) // { ts: "123456789", id: "31ade2" }

* 注意,为了使其按预期工作,脚本不应异步加载,或具有 defer/async 属性。

至于getParams 函数,请随意使用您喜欢的任何实现。例如,从这篇文章开始:How can I get query string values in JavaScript?

【讨论】:

    猜你喜欢
    • 2010-10-23
    • 2012-06-26
    • 2014-11-20
    • 2013-01-08
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多