【发布时间】:2015-02-05 18:48:01
【问题描述】:
我是 Bottle 的新手,也是 Python 的新手,每当我单击按钮时,我都会尝试创建一个应用程序,触发 AJAX 并将 json 发布到服务器并使用 SQLite 存储它。
但是,在当前阶段,我正在尝试弄清楚如何在服务器中成功接收数据。
在客户端, 我有以下用 JavaScript 编写的 send_data 函数。
function send_data(feedback) {
$.ajax({
url: "/feedback",
type: "POST",
data: JSON.stringify(feedback),
contentType: "application/json",
success: function() {
alert("Feedback successfully stored in the server!");
},
error: function() {
alert("Feedback failed to store back in the server!");
},
}
传入的参数feedback 类似于{"id1": 1, "id2": 2}。
在服务器端,我有一个feedback.py 文件,代码是
from bottle import request, route, run
@route('/feedback', method='POST')
def feedback():
comments = request.json
print comments
run(host='localhost', port=8080)
现在,我只想检查我是否成功接收到数据。但是每次,当我点击那个按钮时,我都会收到以下错误
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/feedback. This can be fixed by moving the resource to the same domain or enabling CORS.
OPTIONS http://localhost:8080/feedback [HTTP/1.0 405 Method Not Allowed 2ms]
我不确定是不是因为我没有使用元素<form>。从技术上讲,那个按钮只是一个图像。每次单击该图像时,都会触发 send_data() 函数。
有人可以帮忙吗?对此,我真的非常感激。谢谢!
【问题讨论】:
-
使用表单内容类型会更容易。或者只是不指定一个。或者让你的 python 服务器接受 OPTIONS 请求。
-
您好,请问如何让服务器接受 OPTIONS 请求?我是否将 method='POST' 更改为 method='OPTIONS'?对不起,我是个新手……
-
表单仍然使用 POST,OPTIONS 由浏览器内部发送,用于非标准表单类型,以确保 CORS 功能。您可以使用普通表单标签在没有 CORS 的情况下发布,但您无法从中获得反馈。阅读“启用 cors”;那里有很多,我不知道足够的 python 来编写一个 OPTION 处理程序(尽管我敢肯定它相当简单)
-
感谢您为我指出方向:)。我要试试。
-
请不要张贴文字截图。
标签: javascript python ajax json bottle