【问题标题】:How to response ajax request in Django如何在 Django 中响应 ajax 请求
【发布时间】:2013-01-16 12:27:51
【问题描述】:

我有这样的代码:

$(document).ready(function(){
    $('#error').hide();
    $('#submit').click(function(){
        var name = $("#name").val();
        if (name == "") {
            $("#error").show("slow");
            return false;
        }
        var pass = $("#password").val();
        if (pass == "") {
            $("#error").show("slow");
            return false;
        }
        $.ajax({
            url: "/ajax/",
            type: "POST",
            data: name,
            cache:false,
            success: function(resp){
                alert ("resp");
            }
        });
    });
});

并在 Django 中查看:

def lat_ajax(request):
    if request.POST and request.is_ajax:
        name = request.POST.get('name')
        return HttpResponse(name)
    else :
        return render_to_response('ajax_test.html',locals())

我的错误在哪里?我是Django的初学者,请帮助我。

【问题讨论】:

  • 错误信息是什么?行为?你能发布你的 url.py 吗?
  • csrf 令牌?什么错误?
  • 不是“request.is_ajax”,你需要调用它“request.is_ajax()”

标签: python django


【解决方案1】:

dataType: "json" 放入 jquery 调用中。 resp 将是一个 javascript 对象。

$.ajax({
    url: "/ajax/",
    type: "POST",
    data: name,
    cache:false,
    dataType: "json",
    success: function(resp){
        alert ("resp: "+resp.name);
    }
});

在 Django 中,您必须返回包含数据的 json 序列化字典。 content_type 必须是application/json。在这种情况下,不推荐使用 locals 技巧,因为可能某些局部变量无法在 json 中序列化。这将引发异常。另请注意,is_ajax 是一个函数,必须调用。在你的情况下,它永远是正确的。我也会测试request.method 而不是request.POST

import json
def lat_ajax(request):

    if request.method == 'POST' and request.is_ajax():
        name = request.POST.get('name')
        return HttpResponse(json.dumps({'name': name}), content_type="application/json")
    else :
        return render_to_response('ajax_test.html', locals())

更新:正如 Jurudocs 所述,csrf_token 也可能是我推荐阅读的原因:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

【讨论】:

    【解决方案2】:

    如何创建dict并解析为json:

    name = request.POST.get('name')
    dict = {'name':name}
    return HttpResponse(json.dumps(dict), content_type='application/json')
    

    【讨论】:

    【解决方案3】:

    你有一个错字:

        success: function(resp){
            alert ("resp");
        }
    

    应该是

            success: function(resp){
                alert (resp);
            }
    

    另外,关于csrf,你必须像这样使用header:

        $.ajax({
                url: "some-url",
                headers: {'X-CSRFToken': '{{ csrf_token }}'},
    

    【讨论】:

      【解决方案4】:

      只要这样做...(Django 1.11)

      from django.http.response import JsonResponse
      
      return JsonResponse({'success':False, 'errorMsg':errorMsg})
      

      当你在 jQuery 中处理 json 部分时,做:

      $.ajax({
          ...
          dataType: 'json',
          success: function(returned, status, xhr) {
              var result = returned['success']; // this will be translated into 'true' in JS, not 'True' as string
              if (result) { 
                  ...
              else {
                  ...
              }
          }
      });
      

      【讨论】:

        【解决方案5】:
        $(document).ready(function(){
            $('#error').hide();
            $('#submit').click(function(){
                var name = $("#name").val();
                if (name == "") {
                    $("#error").show("slow");
                    return false;
                }
                var pass = $("#password").val();
                if (pass == "") {
                    $("#error").show("slow");
                    return false;
                }
                $.ajax({
                    url: "/ajax/",
                    type: "POST",
                    data: { 
                        'name': name, 
                        'csrfmiddlewaretoken': '{{csrf_token}}'
                    }, 
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function(data) { 
                        alert(data);
                    },
                    error: function(ts) { 
                        alert(ts);
                    }
                });
            });
        });
        
        
        def lat_ajax(request):
            if request.POST:
                name = request.POST['name']
                return HttpResponse(name)
            else :
                return render_to_response('ajax_test.html',locals())
        

        【讨论】:

          【解决方案6】:

          如果没有任何效果,请将“@csrf_exempt”放在您的函数之前

          from django.views.decorators.csrf import csrf_exempt
          
          @csrf_exempt
          def lat_ajax(request):
          """
          your code
          """
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-07-17
            • 1970-01-01
            • 1970-01-01
            • 2013-04-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-02-04
            相关资源
            最近更新 更多