简体   繁体   中英

Using flask and ajax

I'm serving a web app made with flask. I just added a feature to make a geocoding request to google using ajax. So, pushing a button calls this function in loc_gm.js:

$(function() {
$('#geo_google').click(function() {

    $.ajax({
        url: 'geo_gm',
        data: $('form').serialize(),
        type: 'POST',
        success: function(response) {
            response = JSON.parse(response)
            $('#Lat').val(response['lat']);
            $('#Long').val(response['lng']);
        },
        error: function(error) {
            console.log(error);
        }
    });
});

});

And this is the code in view.py:

@app.route('/geo_gm', methods=('GET', 'POST'))
def geo_gm():
    calle1 = request.form['calle1']
    calle2 = request.form['calle2']
    altura = request.form['altura']

if calle1 and calle2:
    address = '{}+y+{},+CABA,+AR'.format(calle1, calle2)
elif calle1 and altura:
    address = '{}+{},+CABA,+AR'.format(calle1, altura)

url = 'https://maps.googleapis.com/maps/api/geocode/json?address={}&key={}'.format(address, GOOGLE_KEY)
response = requests.get(url)
result = response.json()
return json.dumps(result['results'][0]['geometry']['location'])

This works in my local machine ( I get the coordinates I want from Google), but when I upload it to the server (Digital Ocean), I get this error in the javascript console:

POST http://192.xx.xx.xxx/geo_gm 404 (NOT FOUND)

Being that IP address the one where my app is hosted.

I know this must be a silly mistake I'm making, but I can't figure it out.

Thanks!

Well, I finally found a workaround.

I added in the html file this:

<input type="hidden" id="geo-gm" name="variable" value="{{ url_for('geo_gm') }}">

That way I can have the relative path to geo_gm function. And then in the js file:

$.ajax({
        url: $('#geo-gm').val(),

I did it this way because using {{ url_for('geo_gm') }} directly in the js file didn't work.

Maybe it's not the best way to do it, so if someone has a better way I'll be happy to hear it.

Thanks everybody.

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