Question

I am trying to access a result in a dictionary held in a Python global variable within JavaScript.

var selected = jQuery('.target option:selected').text()
var list = "${c.persons_by_permission["+selected+"]}"

If I directly access the dictionary without the using the variable:

var list = "${c.persons_by_permission['stringID']}"

Then the code works.

However, when I am trying to use the variable to access the dictionary I get a syntax error (I believe its because of the curly braces).

I have tried escaping the braces with:

var list = "${{c.persons_by_permission["+selected+"]}}"

But it gives more syntax exceptions.

Any ideas?

EDIT:

This is not an issue of whether I can use Python and javascript together, it is more of a question of escaping the curly brackets

I am using pylons, so if I try:

alert("${c.persons_by_permission['Documents']}")

I will get the results I need. The issue is that I cannot find a way of passing a variable into the javascript in place of 'Documents'

Was it helpful?

Solution

I'm making a few (reasonable) assumptions here…

  • Your Python is running on your webserver
  • Your JavaScript is running on your client

As far as the Python is concerned it is outputting text. It doesn't care that the browser might interpret it as HTML, JavaScript or whatever. It just generates some text and then sends it to the browser.

With HTTP you get to make a request and have a response. You cannot stop a response half way through to get data back from the client.

You cannot pass data from client side JS back to the Python process that generated the JS. That process will have finished running.

You can either:

  • Send all the data to the client in the first place (and then select the bits you want in JS instead of in Python)
  • Have the JavaScript make a new HTTP request to the server and process the response in JS (this is known as Ajax and there are no shortage of tutorials out there for this)

OTHER TIPS

I don't know what execution environment you are using,but I am almost certain that python and javascript are not executing at the same time.

${c.persons_by_permission['stringID']} looks to me like some kind of template directive. If so, this works because the directive is processed at template processing time. Your other form is just an expression in javascript that evaluates in javascript to a string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top