0

I'm looking for a simple way to assign a value held by a javascript variable to a python variable in a webpy template. I have an int value held by a js variable that I want to use to get an element of a python array. For example (if I want $list[0] in a template):

<script>
...
foo = 0
$i = foo        ??? (doesn't work...)
return $list[ foo ]    ??? (doesn't work...)
...
</script>

Sorry if that isn't as clear as I hope it is. I've tried a ton of different ways to do this, and I can't seem to make it work. Thanks!!!

HPatt
  • 45
  • 3
  • 1
    Sadly, what you want to do inherently does not make sense. Your webpy templates are server-side activities. JavaScript runs once your prepared page has been received by client browsers. There are two separate runtime environments on two separate computers, in other words. You can communicate back to the server with AJAX or WebSockets. – Pointy Oct 21 '13 at 23:57

1 Answers1

0

To expand on Pointy's answer, what you are asking for does not make sense because web pages code is run in a certain order, and you are trying to make it run backwards.

  1. The webserver (python) gets a request. It uses templates to construct a response for that request, and returns and HTML page and sends it to the client. At this point, generally, the python code is done running.

  2. The client (browser) gets the web page. It loads all the other resources it needs to display it, and then runs the javascript.

The javascript and python, therefore, are running on different computers at different times. The solution to your problem is probably going to be a little more complicated then you were hoping for: you have to make a server request from javascript to get the data from the server after the page is loaded on the client, and then manually add it to the DOM.

Community
  • 1
  • 1
kazagistar
  • 1,537
  • 8
  • 20