简体   繁体   中英

How to access fetched data in Ajax response using Django?

i am trying to access data from view function to ajax response.here i am Getting data in my Views.py and i want to access that data in ajax Response. i don't know hoe to do that?
Hare is my Code

in My Views.py

This is My views.py. i am calling this function via ajax.

def myfunction(request):
    if request.method=='POST':
        id=request.POST['id']
        result=MyModel.objects.filter(id=id) # in result variable i am getting all data like fname,,lname etc

here is my AJAX Call

    $.ajax({
            url: '/myfunction',
            method: 'POST',
            data: {
                'id' : id,
                 csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success:function(result)
            {
                alert(result); // here i want to access values
            }
        });
  • in My view.py function , I am getting all data in variable 'result'. i Want to access the all values like fname,lname in my ajax response. 'result' variable is contain a multiple records.i will be thankfull if anyone can help me with this issue.

Your views.py :

from django.http import JsonResponse
def myfunction(request):
    if request.method=='POST':
        id=request.POST['id']
        result=list(MyModel.objects.filter(id=id).values())
        return JsonResponse(result, safe=False)

In your ajax :

    $.ajax({
            url: '/myfunction',
            method: 'POST',
            data: {
                'id' : id,
                 csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success:function(result)
            {
                console.log(result); <--- Here
            }
    });

Here --> Depending upon your response values you will be able to access. Firstly, you have to see how your server is sending data

Refs: JsonResponse | values

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