我正在使用HTML5地理定位来获取用户的位置,然后将lat / long发送到我的django应用程序以查找最近的三所学校。我可以发布lat / long,通过函数运行它以获取最近的学校,并在终端中打印出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)
答案 0 :(得分:2)
如果将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。