简体   繁体   English

如何通过URL将参数传递给GAE上的JavaScript代码?

[英]How to pass a parameter by URL to the JavaScript code on GAE?

I'd like to pass a parameter in request URL to the JavaScript code on GAE environment. 我想将请求URL中的参数传递给GAE环境中的JavaScript代码。

For example, following URL was entered. 例如,输入了以下URL。

http://example.com:8080/hello?key=abc http://example.com:8080/hello?key=abc

The hello page was rendered with hello.py and hello.tmpl which are shown below respectively. hello页面使用hello.py和hello.tmpl呈现,分别如下所示。

'''hello.py'''
key = self.request.get('key')

{# hello.tmpl #} 
<html>
  <div id="key">{{ key }}</div>
  <script src="hello.js"></script>
</html>

In order to refer the key specified with URL in hello.js, the function can be written as following. 为了在hello.js中引用用URL指定的密钥,该函数可以写成如下。

// hello.js
function() {
  console.log($('#key').text());
};

It works well and meets my original request that a parameter was propagated from the URL to the JavaScript Code. 它运行良好,符合我的原始请求,即参数从URL传播到JavaScript代码。

However, I felt like it's not a smart way. 但是,我觉得这不是一个聪明的方式。 I used div tag as a buffer between URL and JavaScript code. 我使用div标签作为URL和JavaScript代码之间的缓冲区。 Does anyone know any smarter way to do this? 有谁知道更聪明的方法吗?

You can use data extension instead of adding a div: 您可以使用数据扩展而不是添加div:

<body data-key='{{key}}'>
  <...>
</body>

// hello.js
function() {
  console.log($('body').data('key'));
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM