【问题标题】:using AJAX to get data from Bottlepy server使用 AJAX 从 Bottlepy 服务器获取数据
【发布时间】: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 &lt;myscriptnamewithoutextension&gt;:app开发。
  • 是的,如果我将 app.get() 更改为 route(),/check 会在浏览器上完美加载。

标签: javascript jquery python ajax bottle


【解决方案1】:

您的问题源于对瓶子应用的一些混淆。

每当您使用 @route (more on this) 时,Bottle 都会为您创建一个默认应用,并在后续调用中隐式重用此默认应用。这种默认应用行为存在于许多函数中(包括hookrun)。

重点是:

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)

【讨论】:

  • 谢谢!!现在工作正常!
猜你喜欢
  • 2023-03-17
  • 2014-05-20
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多