Snir Ben Yosef
Snir Ben Yosef

Reputation: 67

Django Ajax 'GET' return only strings

I am trying to get some data from my database using ajax, and iterate it. for some reason, I get a long string, and not object that I can iterate.

views.py

def postHog(request):
if request.method == 'GET':
    pk = request.GET['megama']
    megama = Speciality.objects.get(id=pk)
    hog = Submain.objects.filter(speciality=megama)
    hogback = []
    for i in hog:
        if (i.image):
            hogback.append({"name": i.name, "desc": 
            i.desc, "image": i.image.url})
        else:
            hogback.append({"name": i.name, "desc": i.desc, "image": "None"})
response_data=json.dumps(hogback,ensure_ascii=False)
return JsonResponse({'hogback': response_data}, status=200,content_type="application/json")

urls.py

path(r'megamas/', views.postHog, name="post_hog"),

myjs.js

 $(".btnsmain").click(function () {
    $.ajax({
        type: 'GET',
        url: "/megamas",
        data:{
            megama:$("#id_main").val()
        },
        success:function (data) {

            $.each(data.hogback, function (index,element) {
                alert(index,element.name);

            });

        },
        error: function (data) {
            alert("not good");

        }
    })
});

if i use alert(hogback[0]) i get the "[" its like i am getting back strings and not the list and dict objects.

thank you!

Upvotes: 0

Views: 750

Answers (2)

l.b.vasoya
l.b.vasoya

Reputation: 1221

Just You Need to parse method of javascript JSON.parse, which identify string and then convert in JSON object

You need edit you success method off ajax like this

        success:function (data) {
           const jsonData = JSON.parse(data)
           alert(jsonData)
           console.log(jsonData[0])
        },

May Be You understand what i said also i gave link see them - enter link description here

If your problem solve then let me know

Upvotes: 0

wfehr
wfehr

Reputation: 2225

json.dumps() returns a json-formatted string.

JsonResponse takes data as a python object, so you don't need to manually convert your data into json. (see docs)

So the following should work:

return JsonResponse({'hogback': hogback}, status=200, content_type="application/json")

Upvotes: 2

Related Questions