elif self.path == "/recQuery":
r = requests.get('http://example.com') # This returns some json from a request to another server.
print r.json()
self.wfile.write(r.json())
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
console.log(http.responseText);
如何使用ajax调用将数据从python服务器发送到javascript。我正在使用的那个不会在控制台中返回任何内容。你能告诉我这里我做错了吗?我需要将来自requests.get方法的响应发送到ajax调用。应该将json返回到ajax调用作为响应。问题是self.wfile.write方法,当我使用这个我没有在JavaScript方面得到任何东西。
答案 0 :(得分:0)
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
我没有在onreadystatechange上获取响应。所以这适合我。谢谢!