从Python传递JSON到JavaScript

OS: Windows 8.1 with update

关键字:Python 3.4,HTML5,JSON,JavaScript

 

1.LocalServer.py,启动server,打开网页,传递JSON。

from threading import Thread
import time
import webbrowser
import http.server
import socketserver
import json
import os

port_number = 8000

server = None
def startServer(port):
    originDir = os.getcwd()
    os.chdir(os.path.dirname(os.path.realpath(__file__)))
    Handler = http.server.SimpleHTTPRequestHandler
    global server
    server = socketserver.TCPServer(("", port), Handler)

    print("serving at port", port)
    server.serve_forever()
    os.chdir(originDir)

def start(port):
    thread = Thread(target=startServer, args=[port])
    thread.start()
    time.sleep(2) #Wait to start the server first

def test():
    if not server:
        print("Failed to start server")

    url = "http://localhost:" + str(port_number) + / + index.html
    url += "?number="
    url += "1"
    
    jsonObj = {
        "person": {
            "name": "Jack",
            "age": 20
        }
    }
    
    jsonStr = json.dumps(jsonObj)
    url += "&person="
    url += jsonStr
    webbrowser.open(url)
    print(url + " is opened in browser")

def stop():
    if server:
        server.shutdown()

if __name__ == "__main__":
    start(port_number)
    test()

2.index.html, 接受JSON string,转换成JSON object。

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>

<body>
    <script>
        function getQueryStringByName(name){
             var result = location.search.match(new RegExp("[\?\&]" + name+ "=([^\&]+)","i"));
             if(result == null || result.length < 1){
                 return "";
             }
             return result[1];
        }
        
        var personStr = getQueryStringByName(person);
        personStr = decodeURIComponent(personStr);
        var personObj = JSON.parse(personStr);
        alert(personStr);
    </script>
</body>
</html>

3.把LocalServer.py和index.html放到同一个文件夹下面。运行LocalServer.py。

4.LocalServer.py也可以被其他py文件调用。例如添加test.py如下

import LocalServer

LocalServer.start(8000)
LocalServer.test()

5.运行test.py,将看到同样的结果。

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。