Javascript 使用AJAX从battlepy服务器获取数据
我正在尝试将json数据从bottlepy服务器检索到网页上。我首先尝试实现一个基本版本,所以只使用字符串。但似乎什么都没有发生。这是代码- HTMLIN包括js-Javascript 使用AJAX从battlepy服务器获取数据,javascript,jquery,python,ajax,bottle,Javascript,Jquery,Python,Ajax,Bottle,我正在尝试将json数据从bottlepy服务器检索到网页上。我首先尝试实现一个基本版本,所以只使用字符串。但似乎什么都没有发生。这是代码- HTMLIN包括js- <!DOCTYPE> <html> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <body>
<!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>
我必须做什么才能访问服务器上的数据?
注意:HTML是一个单独的文件,我希望无论HTML的位置如何,代码都能正常工作
此外,如果这是不可能的,我该如何在模板的帮助下做到这一点 您的问题源于瓶子应用程序的一些混乱 每当您使用@route时,瓶子会为您创建一个默认应用程序,并在后续通话中隐式重用此默认应用程序。此默认应用程序行为存在于许多函数中,包括hook和run 重点是:
app = Bottle() # creates an explicit app
@route('/') # adds the route to the default app
@app.hook('after-request') # adds the hook to the explicit app
run(...) # runs the default app, the hook is not used
要解决您的问题,您有两种选择:
删除对显式应用程序的任何提及;
始终明确使用应用程序
我发现显式地使用应用程序可以更容易地创建子应用程序,并且更清楚地了解发生了什么
新代码:
import bottle
from bottle import response, template, run
app = bottle.Bottle()
@app.hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
# a simple json test main page
str = "Hello"
@app.route('/') #irrelevant to this question. Used this to check server...
def test():
return template('file', str)
@app.get('/check')
def showAll():
return str
run(app=app, host='localhost', port=8080)
您可以从浏览器访问/检查吗?您可能需要使用runapp=app,host=。。。。考虑删除运行…完全,而是使用python-m-blank-reload-debug:app进行开发。是的,如果我更改app,请在浏览器上完全检查加载。转到路线。谢谢!!现在工作很好!
import bottle
from bottle import response, template, run
app = bottle.Bottle()
@app.hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
# a simple json test main page
str = "Hello"
@app.route('/') #irrelevant to this question. Used this to check server...
def test():
return template('file', str)
@app.get('/check')
def showAll():
return str
run(app=app, host='localhost', port=8080)