简体   繁体   中英

JsonResponse doesn't return data in template

I have django 1.7 and I made a view where I want to receive information sent by jquery 2.1.1

I can receive the information in the view and print it, but when I use JsonResponse to send the JSON to my function in the template, and a console.log to view the JSON, nothing happens.

views.py

def filtro(request):
    if request.is_ajax():
        carrera = Event.objects.filter(category__name = request.GET['id'])
        reponse = JsonResponse({'name' : carrera.name, 'age' : carrera.summary})
        return HttpResponse(response.content)
    else:
        return ('/')    

urls.py

url(r'^filtro/$', 'apps.eventos.views.filtro', name="filtro"),

eventos.html

$('.list li a').on('click', Filtrar);
  function Filtrar(){
    var id = $(this).text()
    $.ajax({
      data : {'id' : id},
      url : '/filtro/',
      type : 'get',  
      success: function(data){
        console.log(data);
      }
    });

  };

When someone clicks on any a tag, I want to show the information by JSON from my models.

Prevent the default click event

$('.list li a').on('click', Filtrar);
  function Filtrar(e){
    e.preventDefault();
    var id = $(this).text()
    $.ajax({
      data : {'id' : id},
      url : '/filtro/',
      type : 'get',  
      success: function(data){
        console.log(data);
      }
    });

  };

return a json response

return JsonResponse({'name' : carrera.name, 'age' : carrera.summary})

I don't know python but for you jquery ajax call i think data : {'id' : '\\"'+ id + '\\"'}, instead of data : {'id' : id}, would solve your issue.

Because you are sending a string so you need to add it inside quotations sign.

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