我在HTML / Javascript中创建了一个基本按钮,当我点击按钮时,它应该用Python脚本打印Hello World,但我不知道如何打印它。在代码中我应该放置打印功能,它应该如何?经过一些研究后,我构建了我的Python代码:
import BaseHTTPServer
import SocketServer
HOST_NAME = 'localhost' # !!!REMEMBER TO CHANGE THIS!!!
PORT_NUMBER = 4499 # My localhost is 8080 but if I put 8080 I get an error
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
def do_GET(s):
"""Respond to a GET request."""
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write("<html><head><title>Example</title>")
s.wfile.write("<script type=\"text/javascript\"> function myFunction(){document.getElementById(\"demo\").Example.py=\"Hello World\";}</script></head>")
s.wfile.write("<body> <button onclick = \"myFunction()\">Click to print</button> <p id=\"demo\"></p>")
# If someone went to "http://something.somewhere.net/foo/bar/",
# then s.path equals "/foo/bar/".
s.path = '/Programming for WEB - CTU/Primjer.php'
s.wfile.write("</form></body></html>")
print # How to print the result of myFunction
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
这是我的HTML代码:
<html>
<head>
<title>Example</title>
<script type="text/javascript">
function myFunction(){
document.getElementById("demo").Example.py="Hello World";
}
</script>
</head>
<body>
<button onclick = "myFunction()">Click to print</button>
<p id="demo"></p>
</body>
</html>
我不知道我的代码是否合适,所以如果您有任何建议,请与我分享。