簡體   English   中英

使用燒瓶和ajax

[英]Using flask and ajax

我正在使用Flask開發的網絡應用。 我剛剛添加了一項功能,可以使用Ajax向Google進行地理編碼請求。 因此,按下按鈕會在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);
        }
    });
});

});

這是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'])

這可以在我的本地計算機上運行(我從Google獲得了我想要的坐標),但是當我將其上傳到服務器(Digital Ocean)時,我在javascript控制台中收到了此錯誤:

POST http://192.xx.xx.xxx/geo_gm 404(未找到)

作為該IP地址的宿主我的應用程序。

我知道這肯定是我犯的一個愚蠢的錯誤,但我無法弄清楚。

謝謝!

好吧,我終於找到了解決方法。

我在html文件中添加了以下內容:

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

這樣我就可以擁有geo_gm函數的相對路徑。 然后在js文件中:

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

我這樣做是因為直接在js文件中使用{{url_for('geo_gm')}}無效。

也許這不是最好的方法,所以如果有人有更好的方法,我會很高興聽到。

謝謝大家。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM