如何使用jquery

时间:2018-06-14 09:02:31

标签: jquery ajax

我一直在用纯Django(没有js的django)练习一段时间。因此我决定更进一步将Jquery Ajax包含在我的django中。我可以在我的html中动态插入一些数据

然而问题是使用jquery ajax循环遍历django模型响应对我来说不起作用。 下面是我的jquery.Somebody使用jquery帮助完成数组。

    function ajaxLoad(item){

    $.ajax({
        type:  'POST',
        url :   '../ajax/fetch_category/',
        data: {
            'parameter':item
        },
        cache:false,
        dataType: 'json',
        success: function(response_data) {
        //This is an example of respone data i get from ajax , though was created manually
        var data = [
            {
                "model": "gallery.photogallery",
                "pk": 2,
                "fields": 
                    {
                        "title": "This is my title", 
                        "picture_choices": "Urban", 
                        "description": "This is my good description .",
                        "user": 2, 
                        "date_posted": "2018-06-13T20:13:57.774Z",
                        "views": 3,
                        "likes": 2, 
                        "country": "AG",
                        "slug": "this-is-my-title"
                    }
            }

        ];
       //here am looping through the array
        for( item in data){
            console.log(item);
            $.each(item, function( key, value ) {
                console.log( key + ": " + value );
            });
        }


        },
        error: function(XMLHttpRequest,textStatus,errorThrown) {
            console.log("XMLHttpRequest", XMLHttpRequest);
            console.log("textStatus", textStatus);
            console.log("errorThrown", errorThrown); 
        }
    });
}

2 个答案:

答案 0 :(得分:1)

jQuery中dataType方法的ajax参数设置了您希望从服务器返回的数据类型。您已将其设置为“text”,这意味着jQuery将响应视为纯文本。这没用,特别是如果你想把它当作一个对象并迭代它的键。

虽然你没有展示你认为有用的视图,但我认为你实际上是在发送JSON。在这种情况下,您应该将该参数设置为"json" - 或者将其完全保留,在这种情况下,jQuery将进行智能猜测。

答案 1 :(得分:0)

您从Django获得的内容取决于您在视图中返回的内容。 使用render()快捷方式,您将获得HttpResponse个对象。

对于Ajax,我倾向于返回JsonResponse个对象。

如果您返回纯粹的查询集,则必须先通过serializer传递它们。