簡體   English   中英

在Django中的AJAX POST請求后重新加載模板

[英]Reload template after AJAX POST request in Django

我正在使用HTML5地理位置來獲取用戶的位置,然后將經/緯度發送到我的django應用中以查找最近的三所學校。 我能夠發布緯度/經度,通過一個函數運行它以獲取最近的學府,並在終端中打印dict對象,但是模板永遠不會重新加載新的context_dict數據。

HTML

{% csrf_token %}
<input id = 'button' type="submit" value="Use current location" onclick = 'find_school()' class="btn btn-default">

JS

function find_school(){

function send_off(lat, long){
    var locale = [lat, long];
    console.log(lat, long);
    return locale
}

navigator.geolocation.getCurrentPosition(function(position) {
    $.ajax({
        type: "POST",
        url: "/schools/search/",
        data: {
            csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
            lat_pos: position.coords.latitude,
            long_pos: position.coords.longitude
        },
        success: function(data){
            console.log(data);
        }
    })
});

}

views.py

def find_school(request):
    context = RequestContext(request)
    search_school_list = search_school_bar()
    if request.GET:
        address = request.GET['q_word']
        close_schools = geolocate(address)
        context_dict = {'close_schools': close_schools, 'search_schools':json.dumps(search_school_list)}
    elif request.method == 'POST' and request.is_ajax():
        position = request.POST

        #the geo_search view takes the lat and long
        return geo_search(request, position['lat_pos'],position['long_pos'] )
    else:
        context_dict = {'search_schools':json.dumps(search_school_list)}

    return render_to_response('school_data/search.html', context_dict, context)

def geo_search(request, lat, long):
    context = RequestContext(request)
    search_school_list = search_school_bar()

    close_schools = geolocate_gps(lat, long)

    context_dict = {'close_schools': close_schools, 'search_schools':json.dumps(search_school_list)}
    #This print statement returns in my terminal the results, and they are correct. I just need to reload the template to display the results.
    print context_dict
    #This isn't re-rendering the page with the correct context_dict. It is doing nothing.
    return render_to_response('school_data/search.html', context_dict, context)

如果將render_to_response的輸出返回給ajax調用,則將HTML作為JavaScript調用中“ success:function(data)”中的“ data”元素返回。 如果您的目標是重新加載頁面,我認為您不想使用AJAX。

您應該具有以下內容:

navigator.geolocation.getCurrentPosition(function(position) {
 var form = $('<form action="/geosearch/" method="POST"></form>');
 var long =$('<input name = "long" type="hidden"></input>');
 var lat =$('<input name = "lat" type="hidden"></input>');
 lat.val(position.coords.latitude);
 long.val(position.coords.latitude);
 form.append(lat, long);
 $('body').append(form);
 form.submit();
}

而且,您在/ geosearch /處的視圖應采用post變量,執行您想要執行的所有操作,然后執行render_to_response。

暫無
暫無

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

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