渲染Django的字典,阿贾克斯 [英] render django dictionary with ajax
问题描述
我怎么能填充选择标记
或 UL和李标签
与发送到Django和AJAX请求,则返回JSON(也可以是从一个模型)。我不希望使用其他模板填充这些。
例如:
如果返回的是数据
从Ajax请求
我怎么能做到这一点:
<选择一个id ='carid'>
{%的汽车在轿车%}
<期权价值={{car.name}}> {{car.name}}< /选项>
{%ENDFOR%}
< /选择>
但我不希望从Django的返回HTML或加载另一个HTML仅此标记。
这是我的回答方法
高清car_view(要求)
car_obj = cars.objects.get(名称=汽车)
allmodels = CarModel.objects.filter(轿车= car_obj)
数据= serializers.serialize(JSON,allmodels)
返回的Htt presponse(数据)
这是怎么数据
看起来
[{PK:3,模式:alongjs.carmodel,田:{车:2,名:城市无限 }},{PK:4,模式:alongjs.carmodel,田:{车:2,名:山与城市}}]`
如果您发送带有的 AJAX 要求://api.jquery .COM / jquery.ajax /相对=nofollow> jQuery.ajax()
(看起来你是从previous问题判断) - 你可以添加一些JavaScript的成功回调函数内部遍历 JSON
响应并填充选择
选项。
$。阿贾克斯({
键入:GET,
网址:...
数据: {},
成功:功能(数据){
$每个(数据,函数(){
$('#carid)
.append($(<选项>< /选项>中)
.attr('价值',这个['域'] ['名称'])
的.text(本['域'] ['名称']));
});
}
});
您可以看到一个人为的小提琴例如这里。
您也许可以提高你的JSON虽然 - 因为所有你需要的是车名
。how can i populate the select tag
or ul and li tag
with ajax request sent to django and it returns json ( may also be from a model ). i do not want to use another template for populating these.
example :
if the return is data
from ajax request
how can i do this :
<select id = 'carid'>
{% for car in cars %}
<option value="{{ car.name }}">{{ car.name }}</option>
{% endfor %}
</select>
but i do not want to return html from django or load another html only for this tag.
This is my Response method
def car_view(request)
car_obj = cars.objects.get(name = car)
allmodels = CarModel.objects.filter(car = car_obj)
data = serializers.serialize("json", allmodels)
return HttpResponse(data)
this is how data
looks like
[{"pk": 3, "model": "alongjs.carmodel", "fields": {"car": 2, "name": "city-unlimited"}}, {"pk": 4, "model": "alongjs.carmodel", "fields": {"car": 2, "name": "hill-to-city"}}]`
If you are sending an ajax
request with jQuery.ajax()
(looks like you are judging from previous questions) - you can add some JavaScript inside the success callback function to iterate over the JSON
response and populate your select
options.
$.ajax({
type: 'GET',
url: ...,
data: {},
success: function(data) {
$.each(data, function() {
$('#carid')
.append($("<option></option>")
.attr('value', this['fields']['name'])
.text(this['fields']['name']));
});
}
});
You can see a contrived fiddle example here.
You can probably improve your JSON though - as all you need is the car name.
这篇关于渲染Django的字典,阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!