![](/img/trans.png)
[英]How to get **nested** objects as JSON from Ruby on the backend to AJAX in the front-end
[英]How to get description of object from python django backend to AJAX in front end?
在模型中,我指定了对象描述
def __unicode__(self): ...............................
我想在由Ajax生成的动态投递箱中看到此描述。 但是我只是在下拉列表中得到了[object Object]。
我的数据按以下方式流动:
1-我的api中有消毒器
class LeaseTermSerializer(serializers.ModelSerializer):
class Meta:
model=LeaseTerm
fields = '__all__'
2-我有api方法
@api_view(['GET']) @csrf_exempt def get_leaseterm(request, tid):
leasetermobj = LeaseTerm.objects.filter(lease=tid,is_active = True)
leaseterm_serializer = LeaseTermSerializer(leasetermobj, many=True)
response = Response(leaseterm_serializer.data)
return Response(response.data,status=status.HTTP_200_OK)
3-在我的模板中,我像这样构建它
function getleaseterm() {
//get a reference to the select element
$select = $('#leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
l_url = "/api/get_leaseterm/"+l_id+"/";
$.ajax({
url: l_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val + '</option>');
})
},
});
}
问题是,如果我不指定要显示的字段,则我在下拉列表中显示的“ val”值将在下拉菜单中显示所有我为对象指定的对象的描述时,将为下拉列表中的所有值显示[object Object]模型。
如何在下拉菜单中查看对象描述?
在您的情况下, val
是serializer.data
(由序列化程序声明表示json对象),因此结果是[object Object]
,您在使用django模板时会感到困惑。 但是可以,将charfield添加到序列化器中并使用它
as_char = serializers.CharField(source='__unicode__')
在html中:
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
它显示[object Object]
因为您的get_leaseterm
端点返回序列化为JSON对象的LeaseTerm
列表,并且您将对象本身添加到option
元素内容中。
您定义的python方法在客户端不可用。 要解决您的问题,您有2种解决方案:
__unicode__
方法中的逻辑。 或最好:
field
(可能将该方法设置为@property
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.