我正在尝试使用BaseHTTPRequestHandler在POST请求之后检索响应。为了简化这个问题,我有两个PHP文件。
jquery_send.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function sendPOST() {
url1 = "jquery_post.php";
url2 = "http://localhost:9080";
$.post(url1,
{
name:'John',
email:'john@email.com'
},
function(response,status){ // Required Callback Function
alert("*----Received Data----*\n\nResponse : " + response + "\n\nStatus : " + status);
});
};
</script>
</head>
<body>
<button id="btn" onclick="sendPOST()">Send Data</button>
</body>
</html>jquery_post.php
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: ". $name . ", email: ". $email; // Success Message
}
?>使用jquery_send.php,我可以向jquery_post.php发送一个POST请求并成功地检索该请求。现在,我希望得到相同的结果,将POST请求发送到Python而不是BaseHTTPRequestHandler。我使用这个Python代码来测试:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
print("\n----- Request Start ----->\n")
content_length = self.headers.getheaders('content-length')
length = int(content_length[0]) if content_length else 0
print(self.rfile.read(length))
print("<----- Request End -----\n")
self.wfile.write("Received!")
self.send_response(200)
port = 9080
print('Listening on localhost:%s' % port)
server = HTTPServer(('', port), RequestHandler)
server.serve_forever()我可以得到POST请求,但是我无法检索响应(“收到了!”)在jquery_send.php中。我做错了什么?
编辑:
简而言之,我使用BaseHTTPRequestHandler来获取POST请求并发送响应,这是一段很小的Python代码。
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
print(self.rfile.read(int(self.headers['Content-Length'])).decode("UTF-8"))
content = "IT WORKS!"
self.send_response(200)
self.send_header("Content-Length", len(content))
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(content)
print "Listening on localhost:9080"
server = HTTPServer(('localhost', 9080), RequestHandler)
server.serve_forever()我可以用卷发得到回应
curl --data "param1=value1¶m2=value2" localhost:9080但是我无法使用ajax/jquery从网页中获得它(服务器接收POST请求的正确性,但是网页没有检索响应)。我该怎么做呢?
发布于 2015-11-30 20:29:08
好的,问题是CORS头,只要我是从不同的端口(或类似的.)请求。这个问题解决了,加上
self.send_header('Access-Control-Allow-Credentials', 'true')
self.send_header('Access-Control-Allow-Origin', '*')我的响应标头。
https://stackoverflow.com/questions/33673168
复制相似问题