Passing a python variable to a javascript function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • neeebs
    New Member
    • Feb 2008
    • 1

    Passing a python variable to a javascript function?

    Hi,

    I'm not sure if this is a javascript problem per se, but here goes. I have an xsl document with a python function defined within a <script> block. Elsewhere in the xsl file, within a python script block, I call the python function and store the return value in a variable. I need to be able to display this returned value on the webpage that the xsl generates. I tried to do a document.write([python returned variable]) but found that document.write( ) causes firefox to hang when used within an xsl file. So instead I used document.getEle mentById().inne rHTML to display the python returned value. This works in ie7 but in firefox the output is blank. So the problem is that internet explorer is letting me pass a variable that was given a value from a python function return value and firefox is not letting me jumble the types as such.

    Heres a very simplified version of the problem:

    [HTML]<html>
    <span id="out">This text will be replaced</span>

    <script language="Pytho n" type="text/python">
    import sample
    text = sample.get_stri ng()
    document.getEle mentById("out") .innerHTML = text
    </script>
    </html>
    [/HTML]
    import sample, imports a file called sample.py which is located in the same directory. It is just:

    [CODE=python]#sample.py
    def get_string():
    return "ABCD"
    [/CODE]

    I want the text in <span id="out"> to be replaced by the "text" variable in the script block. This does not work in firefox however it does work in ie. I'm looking for a solution that works in both browsers obviously. This example is embedded in an html block but in the full version, the html is embedded in an xsl stylesheet.

    I'm really stuck here and the only other option I can think of is to rewrite the python function in javascript but this would be my last resort as the real python function is pretty complex.

    Is there any way to pass the python variable to the javascript function call?

    Thanks in advance
    Last edited by acoder; Feb 25 '08, 07:43 AM. Reason: Added code tags
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    I don't know if this will help, but the span should be within body tags.

    Not really dabbled with Python, but, generally speaking, when you need to pass a server-side function to JavaScript, you use the server-side language to generate the JavaScript. I'm not sure if Python fits into this.

    Comment

    • Irfan Younas
      New Member
      • Jul 2010
      • 1

      #3
      You can use JSON

      USING JSON/simplejson u can dump the python data structure into JSON data structure, which can be accessed in javascript.

      Comment

      Working...