简体   繁体   中英

How to render data in django to AJAX?

I am trying to send a json value to ajax from django class based view and the data i am sending will be appended in html through ajax. but i am not able to send value from back end to front end successfully.

class DetailView(TemplateView):
    template_name = 'list.html'

    def get_context_data(self,*args, **kwargs):
        context = super(DetailView,self).get_context_data()
        list_view = GetList().get_data(self.request)
        movie_list = list.json()
        context['list']= movie_list
        print(movie_list)
        return context

So this code is sending only template value to the ajax data, when i do the console.log(data) on success call it shows me whole html code of the 'list.html' in both alert and console.log . But it prints all the values in cmd console.

cclass DetailView(TemplateView):
    template_name = 'list.html'


    def get(self,request):
        list_view = GetList().get_data(self.request)
        movie_list = list.json()
        return HttpResponse(json.dumps(movie_list))

this code prints all the values on respective html, but doesnt call ajax function.so no values showing in console.log.

this is my ajax call,first i am trying to just see weather i'm successfully getting the values on success call or not.

<script>
    $(document).ready(function(){
        $.ajax({
            method :'GET',
            url: '/detail',

            success: function(data){
            alert(data)
            console.log(data)
            },
        })
    })
</script>

So, how can i achieve my desired result? I want to get value in ajax call so i cal show those values in a table which is in a list form

You can use JsonResponse to send json data. (You can see detail in docs here )

like below

from django.http import JsonResponse

class DetailView(TemplateView):
template_name = 'list.html'

def get(self,request):
    list_view = GetList().get_data(self.request)
    movie_list = list.json()
    return JsonResponse(movie_list, status=200)

btw, you have to aware your data type. JsonResponse automatically serialize your data so you don't have to use json() for your data.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM