從Python傳遞JSON到JavaScript

來源:互聯網
上載者:User

標籤:

OS: Windows 8.1 with update

關鍵字:Python 3.4,HTML5,JSON,JavaScript

 

1.LocalServer.py,啟動server,開啟網頁,傳遞JSON。

from threading import Threadimport timeimport webbrowserimport http.serverimport socketserverimport jsonimport osport_number = 8000server = Nonedef 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 firstdef 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 LocalServerLocalServer.start(8000)LocalServer.test()

5.運行test.py,將看到同樣的結果。

 

從Python傳遞JSON到JavaScript

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.