【问题标题】:How to send JSON response from python server to the javascript using ajax call如何使用ajax调用将JSON响应从python服务器发送到javascript
【发布时间】:2016-06-06 14:28:14
【问题描述】:
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 端没有得到任何东西。

【问题讨论】:

  • 目前还不清楚您要做什么。第一个sn-p是什么?你在用requests.get()做什么?
  • http.responseText 需要在 http.onreadystatechange 回调中,如果您发送 JSON,则内容类型应该是 application/json。
  • 我进行了编辑只是为了让我的问题更清楚。
  • 谢谢@jcubic。现在工作得很好。

标签: javascript python json ajax


【解决方案1】:

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 的响应。所以这对我有用。谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2020-02-28
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2011-10-28
    相关资源
    最近更新 更多