我正在学习 JQuery Get 方法。我启动了一个 Python HTTP 服务器:
(只需输入命令“Python -m SimpleHTTPServer”)。
只需在我的网络浏览器上访问“http://localhost:80”即可测试此网络服务器。但是,当我编写这个非常简单的 javascript 来访问我的网络服务器时。我收到一条错误消息:
“代码 501,消息不支持的方法('OPTIONS')”
我使用假设跨域请求 JQuery 的 jquery.xdomainajax.js 库。
这是我的javascript代码:
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.xdomainajax.js"></script>
<script type="text/javascript">
$(document).ready(function(){
u = 'http://localhost:80';
jQuery.get(u, function(res){
$("#data").html(res.responseText)
});
});
</script>
</head>
<body>
<p id="data"></p>
</body>
</html>
实际上,如果我将 u 更改为任何其他 url,例如“http://www.google.ca”。它工作得很好。但我不知道为什么它不适用于基本的 Python HTTP 服务器。谁能帮帮我?
最佳答案
我所做的是编写一个自定义的HTTPRequestHandler。我在 MyHandler 中添加了一个 do-OPTIONS 方法来告诉浏览器我的服务器支持 CORS。这是通过发送 header Access-Control-Allow-Origin、Access-Control-Allow-Methods 和 Access-Control-Allow-Headers 来完成的。此外,我在 do_GET 方法中添加了“self.send_header('Access-Control-Allow-Origin', '*')”语句。
class MyHandler(BaseHTTPRequestHandler):
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
self.end_headers()
def do_GET(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write("<html><body>Hello world!</body></html>")
self.connection.shutdown(1)
关于javascript - 奇怪的 JQuery 错误 "code 501, message Unsupported method OPTIONS",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8470414/