For example I have this in my template:
{% for pins in data %}
<option type="text" value="{{pins.clandpin}}">{{pins.clandpin}}</option>
{% endfor %}
And in my view.py:
def section_landpins(request):
if request.method == "GET":
section_id = request.GET['sectionid']
m = ButuanMaps.objects.filter(ssectionid=section_id)
data = serializers.serialize("json", m)
return HttpResponse(data, content_type='application/json')
How do I use the response from my view.py in my template using AJAX?
$(document).ready(function(){
$("#formsection").change(function() {
$('#forminput').empty();
$.ajax({
url : "/sectionpins",
type : "GET",
dataType: "json",
data : {
'sectionid' : $(this).val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success : function(data){
......
},
error: function (){
alert('error');
}
});
return false;
});
});
If you render the from to a string like this, you can than put the HTML directly into the form,
def section_landpins(request):
if request.method == "GET":
section_id = request.GET['sectionid']
pins = ButuanMaps.objects.filter(ssectionid=section_id)
html = render_to_string('pathToTemplate', {'pins ': pins })
return HttpResponse(html)
Take the rendered HTML and put it into whereever you see fit using selectors.
$(document).ready(function(){
$("#formsection").change(function() {
$('#forminput').empty();
$.ajax({
url : "/sectionpins",
type : "GET",
dataType: "json",
data : {
'sectionid' : $(this).val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success : function(data){
$('form').html(data);
},
error: function (xhr, textStatus, thrownError){
alert("xhr status: " + xhr.statusText);
}
});
return false;
});
});
you can test if a request use ajax
def section_landpins(request):
if request.method == "GET":
section_id = request.GET['sectionid']
m = ButuanMaps.objects.filter(ssectionid=section_id)
data = serializers.serialize("json", m)
if request.is_ajax():
return HttpResponse(data, content_type='application/json')
else:
rendre_to_response(........)
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.