简体   繁体   中英

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.

For example, following URL was entered.

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

The hello page was rendered with hello.py and hello.tmpl which are shown below respectively.

'''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
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.

However, I felt like it's not a smart way. I used div tag as a buffer between URL and JavaScript code. Does anyone know any smarter way to do this?

You can use data extension instead of adding a div:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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