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!