我正在寫一個簡單的網絡服務器。這是Python代碼,我有:網絡服務器 - 如何指定服務器使用
import http.server
from os import curdir, sep
class RequestHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path.endswith(".php"):
f = open(curdir + sep + self.path)
self.send_response(200);
self.send_header("Content-type", "text/php")
self.end_headers()
self.wfile.write(f.read())
f.close()
else:
self.send_error(404, "Cannot open non-html file")
httpd = http.server.HTTPServer(("", 8000), RequestHandler)
httpd.serve_forever()
這是HTML代碼:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<input type="button" value="Click me" id="button">
<script>
var buttonOnClick =
function() {
var updateButton =
function(result) {
$("#button").replaceWith("<p>" + result + "<p>");
};
$.get("text.php", updateButton);
};
$("#button").click(buttonOnClick);
</script>
</body>
</html>
text.php
<?php
echo "Hello!";
?>
當我與Apache上運行此,我得到的預期成績。該按鈕變成「你好!」當你點擊它。但是,當我使用Apache運行它時,頁面顯示ERR_CONNECTION_REFUSED錯誤。這告訴我,我的網頁使用Apache作爲服務器,而不是我的Python代碼。我無法弄清楚如何讓我的HTML和jQuery代碼使用我的自定義web服務器而不是Apache。這可能是一個非常簡單的問題,但我很難過。
如果我的代碼中有任何可以改進的地方,請告訴我。
定製服務器在端口8000。你把'運行:8000'在URL中的服務器名稱後? – Barmar
我嘗試使用'https:// localhost:8000/webprograms/testwebserver/index.html'。它給了我一個SSL連接錯誤。 – M3579