【发布时间】:2014-06-01 11:01:12
【问题描述】:
我在python中的bottle中编写了一个代码,它从mongodb获取数据,当用户从bottle中请求urlhttp://localhost:8080/index/test时,它将从mongoDB返回json结果。当我将浏览器指向该 url 时它工作正常,我可以在浏览器上看到所有结果。
但是,当我尝试从 jQuery ajax 发送请求时,我总是会出错,并且请求永远不会成功。
有没有人做过类似的事情可以和我分享他们的方法?
我的一般问题是,当使用瓶子作为服务器时,从客户端从 MongoDB 获取数据的最佳方式是什么。我在 Node.js 中看到了一些示例,但我想使用 python 作为服务器。
我已经使用了这个代码。
$.ajax({
type: "POST",
url: "http://localhost:8080/hello/test",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("success");
},
error: function (response){
console.log("failed");
}
});*/
我也试过这个:
$.post( "http://localhost:8080/hello/test", d)
.done(function( response ) {
console.log("success");
});
这些都不行。我也尝试过 GET 而不是 post,但没有运气。
这就是我在 python 方面所拥有的:
从瓶子导入路线,运行,模板
@route('/hello/<name>')
def index(name):
return {'status':'online', 'something':'blah blah'}
run(host='localhost', port=8080)
非常感谢。
【问题讨论】:
-
你能粘贴你正在使用的jquery AJAX代码吗?
-
非常感谢@LalitAgarwal 的评论。我已经用我使用的 ajax 代码更新了我的帖子。
-
Python 肯定会返回 JSON 吗?出错时您会看到什么响应。
-
检查 gulty 的答案,我相信这是一个 CORS 问题。如果您的应用程序未在 8080 上运行,则除非您允许 cors,否则您将无法访问 8080 端口。检查浏览器的投诉(如果是 chrome ctr shift j 将启动开发工具),我相信您会看到类似:
No 'Access-Control-Allow-Origin' header is present on the requested resource. -
@sWW 是的,它正在返回 JSON,当我转到浏览器并输入 URL 时,它会显示一个充满 JSON 对象的页面。
标签: javascript jquery mongodb bottle