简体   繁体   中英

How to use ajax with blueprints in flask

I would like to define a global ajax function that I will use to unlock models in case a window closes unexpectedly.

@main.route('_unlockmodels')
def unlockmodels():
    .. unlock stuff ..
    return None

and then the actual ajax

function unlockModel() {
    $.ajax({
        type: "get",
        url: "main/_unlockmodels"
    }).done(function(data) {
        console.log('well see if your locks are gone', data, '<-- data?')
    });
}

Problem is, wherever I call this function from (in another blueprint) I get the following error

GET http://127.0.0.1:5000/otherblueprint/page/main/_unlockmodels

How to specify where I am currently calling from (or other way to fix this)?

I call the function from within my page's javascript like

window.onbeforeunload = unlockModel;

You are using a relative URL; it'll always be different depending on the current page URL. This has nothing to do with blueprints.

Use an absolute URL, or better still, have Flask give you the URL for the AJAX view:

function unlockModel() {
    $.ajax({
        type: "get",
        url: {{ url_for('unlockmodels')|tojson|safe }}
    }).done(function(data) {
        console.log('well see if your locks are gone', data, '<-- data?')
    });
}

The url_for() call returns a string with the proper absolute URL for the view you registered, and |tojson|safe produces a valid JavaScript string for that URL to insert into your jQuery code.

If your JavaScript is not part of a template, put the URL on an element in HTML that is generated by the template. Put it in a data attribute on the body, for example:

<body data-unlockmodels="{{ url_for('unlockmodels') }}">

then retrieve that value from the body when you need to:

function unlockModel() {
    $.ajax({
        type: "get",
        url: $('body').data('unlockmodels')
    }).done(function(data) {
        console.log('well see if your locks are gone', data, '<-- data?')
    });
}

However, if you are trying to do this when unloading the window, you'll have to set the async flag to false to make sure it gets to complete before the page is torn down, see $(window).unload wait for AJAX call to finish before leaving a webpage :

function unlockModel() {
    $.ajax({
        type: "get",
        url: $('body').data('unlockmodels'),
        async: false
    }).done(function(data) {
        console.log('well see if your locks are gone', data, '<-- data?')
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM