【问题标题】:I wanted to get data from server using flask and jQuery我想使用flask和jQuery从服务器获取数据
【发布时间】:2016-12-01 02:16:40
【问题描述】:

所以我在下面尝试了javascript

$(document).ready(function () {
    $("#mtime").bind("click", function (e) {
        $.getJSON('/test', function(data){
            if(data.result==15){
                alert("success!");
            }else{
                alert("fail....");
            }
        });
    });
});

并像这样使用烧瓶制作路线

@app.route('/test',methods=[GET,POST])
def test():
    return jsonify(result=15)

但是当我点击 'mtime' 时,警报方法不起作用。 并从 cmd 窗口收到此消息

"GET /test HTTP/1.1" 404 -"

我怎样才能让它工作?

【问题讨论】:

  • @app.route('/test', methods=['GET', 'POST'])?

标签: javascript jquery python flask server


【解决方案1】:

正如 PJ Santoro 所写,GET 和 POST 周围缺少引号。但是,您不需要显式添加方法,因为您只需发出 GET 请求,这是默认的。

from flask import Flask, render_template, jsonify


app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/test')
def test():
    return jsonify(result=15)


if __name__ == '__main__':
    app.run(host='localhost', port=5000, debug=True)

如果您在 HTML 文件中使用 url_for 来为您的端点生成 url,这也是更好的做法。这样,当您决定更改子域或使用蓝图时,您可以确保 url 发生变化。

$(document).ready(function () {
$("#mtime").bind("click", function (e) {
    $.getJSON({{ url_for('test') }}, function(data){
        if(data.result==15){
            alert("success!");
        }else{
            alert("fail....");
        }
    });
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    相关资源
    最近更新 更多