標籤:
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