【发布时间】:2014-06-24 16:25:19
【问题描述】:
我正在尝试将 json 数据从 Bottlepy 服务器检索到网页上。我试图首先实现一个基本版本,所以只尝试了字符串。但似乎什么都没有发生。这是代码 -
HTML(包括js) -
<!DOCTYPE>
<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<body>
<script>
function print()
{
$(document).ready(function(){
$.get('http://localhost:8080/check', function(result){
alert('success');
$('#main').html(result);
});
});
}
print();
</script></body>
</html>
python 代码 -
from bottle import Bottle, route, get,request, response, run, template
app = Bottle()
@app.hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
# a simple json test main page
str = "Hello"
@route('/') #irrelevant to this question. Used this to check server...
def test():
return template('file', str)
@app.get('/check')
def showAll():
return str
run(host='localhost', port=8080)
我必须做什么才能访问服务器上的数据? 注意:HTML 是一个单独的文件,我希望无论 HTML 的位置如何,代码都能正常工作。
另外,如果这是不可能的,我该如何借助模板来做到这一点?
【问题讨论】:
-
你能从浏览器访问
/check吗?您可能需要使用run(app=app, host=...)。考虑彻底删除run(...),改用python -m bottle --reload --debug <myscriptnamewithoutextension>:app开发。 -
是的,如果我将 app.get() 更改为 route(),/check 会在浏览器上完美加载。
标签: javascript jquery python ajax bottle