简体   繁体   English

JsonResponse不返回模板中的数据

[英]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 我有Django 1.7,我做了一个视图,我想在其中接收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. 我可以在视图中接收信息并进行打印,但是当我使用JsonResponse将JSON发送到模板中的函数以及使用console.log查看JSON时,什么也没有发生。

views.py 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 urls.py

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

eventos.html 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. 当有人点击任何a标签,我想说明的JSON从我的模型的信息。

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 返回一个json响应

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. 我不知道python,但是对您来说,jQuery ajax调用我认为data : {'id' : '\\"'+ id + '\\"'},而不是data : {'id' : id},会解决您的问题。

Because you are sending a string so you need to add it inside quotations sign. 因为您要发送字符串,所以需要将其添加在引号内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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