如何在ajax调用中使用flask url_for?

时间:2016-11-29 15:45:19

标签: javascript python ajax flask

我有这条路线:

@my_app.route('/get_data'/<ticket_number>)
def get_data(ticket_number):
    response = process_data(ticket_number)
    return response

在模板中,我有这个javascript来调用那条抓取一些数据并返回html的路径:

function updateData() {
    var ticket = document.getElementById('ticket_num');
    console.log(ticket.innerHTML);
    var eventDataBaseUrl = "{{ url_for('get_data') }}"
    var jqxhr = $.ajax(eventDataBaseUrl + "/" + String(ticket.innerHTML) )
    .done(function(data) {
        console.log("done");
        $("#myTable").find('tbody').html(data);
        $("#myTable").trigger('updateAll');
    })
    .fail(function(jqXHR, status, error) {
        console.log("error: " + error);
    })
    .always(function() {
        console.log("complete");
    });
    // Trim data to time window
    // Reload table with trimmed data on interval
    console.log("interval");
}
setInterval(updateData, 300000);

我的问题是使用ticket_number构建网址。

据我所知,这是罪魁祸首:

var jqxhr = $.ajax(eventDataBaseUrl + "/" + String(ticket.innerHTML) )

我有另一条做类似的路线而没有传递看起来像这样的url参数,它工作正常:

var jqxhr = $.ajax("{{ url_for('get_json_data') }}")

这里是完整的追溯:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/vagrant/chg_app/chg_app.py", line 92, in eng_demo
    return render_template('eng_demo.html', result=result)
  File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 134, in render_template
    context, ctx.app)
  File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 116, in _render
    rv = template.render(context)
  File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 989, in render
    return self.environment.handle_exception(exc_info, True)
  File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 754, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/vagrant/chg_app/templates/eng_demo.html", line 1, in top-level template code
    {% extends "base.html" %}
  File "/vagrant/chg_app/templates/base.html", line 73, in top-level template code
    {% block header %}{% endblock %}
  File "/vagrant/chg_app/templates/eng_demo.html", line 258, in block "header"
    var eventDataBaseUrl = "{{ url_for('get_data') }}"
  File "/usr/local/lib/python2.7/dist-packages/flask/helpers.py", line 332, in url_for
    return appctx.app.handle_url_build_error(error, endpoint, values)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1811, in handle_url_build_error
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/helpers.py", line 322, in url_for
    force_external=external)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/routing.py", line 1758, in build
    raise BuildError(endpoint, values, method, self)
BuildError: Could not build url for endpoint 'get_data'. Did you forget to specify values ['ticket_number']?

有没有人知道使用票号参数从javascript调用该路由的正确方法?

1 个答案:

答案 0 :(得分:1)

不是通过在没有参数的情况下使用url_for获取“eventDataBaseUrl”,然后连接ID,而是必须向其传递一个虚拟参数,然后将其替换为您的实际ID。类似的东西:

var eventDataBaseUrl = "{{ url_for('get_data', 'DUMMY_VALUE') }}"
var actualDataUrl = eventDataBaseUrl.replace(/DUMMY_VALUE/, ticket_id)

另请注意,您不应该在那里使用innerHTML;假设ticket_num指的是输入,则应使用.value