简体   繁体   中英

html & javascript to use Python variables in GAE

The code bellow is a part of a Google App Engine project I am building with Python. I am taking input of x and y(not seen here), and printing it here as a table with its x,y coordinate as the text in the table. Additionally, I need to make it so that when you click on a cell of the table, it calls a function which will return a string for it to pop up with. For simplicity at this time it's just the X and Y again.
So in short, I need a way to pass a variable from Python to HTML so it can be passed to javascript. How can I do that?

def testFunc(self, x, y):
        return str(x) + " , " + str(y)
    def drawTable(self, row , col):
        write = self.response.write
        write(row)
        write(col) 
        write("<html><body><script> function tableInfo() { alert(\""+ self.testFunc(x, y)+""\");}</script><table>")
        for y in range(row):
            write("<tr>")
            for x in range(col):
                cell = "<td bgcolor=\"#00FF00\" onclick = \"tableInfo(x, y)\">" + str(x) + " " + str(y) + "</td>"
                if x % 2 == 0:
                    cell = "<td bgcolor=\"#FF0000\" onclick = \"tableInfo(x, y)\">" + str(x) + " " + str(y) + "</td>"
                write(cell)
            write("</tr>")    
        write("</table></body></html>")  

You can write Javascript, substituting values from Python:

write("""<html><head>
    <script>
    var x = %d, y = %d;
    </script>
    </head>""" % (x, y))

Now you can use x and y in other Javascript code.

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