Using Pylons global variables with JavaScript (escaping brackets)

独自空忆成欢 提交于 2019-12-20 07:07:30

问题


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'


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/8834666/using-pylons-global-variables-with-javascript-escaping-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!