jQuery:如何读取Django视图返回的自定义对象?

时间:2012-08-08 13:41:22

标签: jquery django

这是我的django view

@csrf_exempt
@login_required
def get_playlists_for_user(request):
    """
    gets all playlists for user
    """
    logging.info('getting playlist for user - ' + str(request.user))
    playlists = UserPlaylist.objects.get_all_playlists_for_user(request.user)
    logging.info('user=%s, playlists=%s'%(request.user, playlists))
    return HttpResponse(playlists)

以下是jQuery通过ajax

调用它的方式
$.ajax({
        url: '/getUserPlaylists',
        success: function(response, textStatus, jqXHR){

            console.log(response);
        },
        error: function(response, textStatus, jqXHR) {

        }
});

视图返回播放列表对象列表

playlists=[<Playlist id:1, name:first, date_created:2012-08-05 06:28:31.954623+00:00, deleted:False>, <Playlist id:2, name:my, date_created:2012-08-06 12:47:13.023537+00:00, deleted:False>, <Playlist id:3, name:new, date_created:2012-08-06 12:48:45.708277+00:00, deleted:False>, <Playlist id:5, name:second, date_created:2012-08-06 21:19:33.050187+00:00, deleted:False>]

Playlist的架构模型是

class Playlist(models.Model):
    name = models.CharField(max_length=30)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    deleted = models.BooleanField(default=False)

当我将它们记录在萤火虫中时,我将其视为

Playlist objectPlaylist objectPlaylist objectPlaylist object

如何在jQuery中读取这些对象?

1 个答案:

答案 0 :(得分:2)

你需要以一种形式返回Python对象javascript可以理解通常是json(javascript对象表示法)。因此,在您的视图中,使用django的serialisers将您的django查询集转换为json:

from django.core import serializers
...
json = serializers.serialize('json', playlists)
return HttpResponse(json, mimetype="application/json")

并在你的ajax中:

$.ajax({
       url: '/getUserPlaylists',
       dataType: "json",
       success: function(response, textStatus, jqXHR){
           for(var i = 0; i < response.length; i++ ){
               var playlist = response[i]['fields'];
               // Do something now with your playlist object
               console.log(playlist.name);
           }
       },
       error: function(response, textStatus, jqXHR) {
       }
});

这意味着你的ajax response中的success将是这样的(javascript对象列表):

[{ "model" : "playlist.Playlist", "pk" : 1, "fields" : { "name" : "...", ... } }]