zoukankan      html  css  js  c++  java
  • 从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,将看到同样的结果。

  • 相关阅读:
    jquery插件layer
    获取订单的product_id 和订单的数量
    Python psutil模块
    Linuc bazaar命令
    分布式版本控制系统
    launchpad, jira, github
    C/C++ 经典面试题汇总
    Windows Cmder
    Reddit指南
    Linux xclip命令
  • 原文地址:https://www.cnblogs.com/ldlchina/p/4426018.html
Copyright © 2011-2022 走看看