我正在尝试编写一个chrome扩展,它能够向/从python服务器脚本发送/接收数据。目前,我正处于js脚本正在进行GET请求的地步,唯一的问题是.responseText始终为空(即使python脚本正在响应文本)。
popup.js
document.addEventListener('DOMContentLoaded', function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == xhr.DONE) {
var resptxt = xhr.responseText;
if (resptxt) {
document.getElementById('texthtm').innerHTML = resptxt;
} else {
document.getElementById('texthtm').innerHTML = "no response";
}
}
}
xhr.open("GET", "http://127.0.0.1:80", true);
xhr.send();
});
server.py
import time
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
HOST_NAME = "127.0.0.1"
PORT_NUMBER = 80
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write("heyyy")
if __name__ == "__main__":
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
因此每次按下扩展按钮时,它都会显示“无响应”,这意味着请求至少已完成。我在这里做错了什么?