【问题标题】:Json does not work in Django with AjaxJson 在带有 Ajax 的 Django 中不起作用
【发布时间】:2013-08-27 09:46:55
【问题描述】:

我想在 Django 框架中发出 ajax 请求。但是,我不会通过 json 从客户端获取数据。当我不使用 Json 时它可以工作。 如果我在 ajax 中使用带有 {'a':'value'} 的 dataType:'json',我无法在 view.py 中得到它,结果什么都没有...... 但是,如果我在 ajax 中使用 data:$(this).serializeArray(),我可以通过 request.POST 获得结果。但是,我确实需要自定义我的数据并将表单中的数据以外的其他数据发送到我的 view.py。我想发送一个 {'a', 'mydata', 'form': myformdata}... 有办法吗?

模板:

<form id="ajax2" action="/seghca/test-post/" method="post">{% csrf_token %}
Nom : <input type="text" name="nom" value="" id="nom"/><br/>
prenom : <input type="text" name="prenom" value=""/><br/>
<input type="submit" value="Envoyer"/>
</form>


<div id="result"></div>

javascript:

$(document).ready(function(){


        // POST AJAX
        $("#ajax2").submit( function() {
        var urlSubmit = $(this).attr('action');

        var data = $(this).serializeArray();
        data.push({
                key:   "keyName",
                value: "the value"
            });
        $.ajax({  
            type: "POST",
            url: urlSubmit,
            dataType: "json",               
            data      : data,//$(this).serializeArray(),
            success: function(response){
                 var json_response = JSON.parse(response);
                    // now get the variables from the json_response
                    $('#result').html(json_response.html);
            }
        });
        return false;
    });

    });

view.py(ajax启动test_post视图,home2是公式的视图):

from datetime import datetime
from django.http import HttpResponse, Http404
from django.shortcuts import redirect, render
from seghca.models import Article


from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
import json

def home2(request):
    return render_to_response('seghca/form.html', context_instance=RequestContext(request))

@csrf_exempt
def test_post(request):
    data = {'html': request.POST['key']}
    return HttpResponse(json.dumps(data), mimetype="application/json")

【问题讨论】:

标签: ajax django json jquery django-views


【解决方案1】:

当您使用 ajax 视图时,您应该以 json 形式从视图返回数据:

data = {'html': request.POST['input']}
return HttpResponse(json.dumps(data), mimetype="application/json")

其次需要先在客户端解析响应:

success: function(response){
    var json_response = JSON.parse(response);
    // now get the variables from the json_response
    $('#result').html(json_response.html);
}

第三,如果您需要传递表单数据以及更多信息,您可以这样做:

var data = $(this).serializeArray();
data.push({
    key:   "keyName",
    value: "the value"
});

第四个你缺少csrf 令牌。

【讨论】:

  • 我用你的更正编辑了我的代码,但是,它并没有解决问题,views.py 没有收到任何东西!似乎 django 不想得到 json...
  • 请确保您也在发布数据中传递 csrf 令牌。
  • 我用装饰器进行了编辑(对吗?),但它仍然不起作用。
  • 好的,经过多次测试,我发现从客户端到服务器一切正常,我可以得到一个自定义字典。但是从服务器到客户端 json 根本不起作用,如果我删除 json 它可以工作,但是使用 json 我什么都没有。
【解决方案2】:

data: data, 更改为data: {'data': JSON.stringify(data)},

您将能够通过 django 中的POST['data'] 访问数据的序列化版本。请记住,如果您想在 django 中使用它,则必须对其进行反序列化,例如 json.loads(POST['data'])

【讨论】:

    【解决方案3】:

    我有你同样的需求。我的解决方案是:

    AJAX 请求:

        var posturl = $('#'+formid).prop('action');
    
    $.ajax({
            async:false,
            type: "POST",
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            url : posturl,
            data : $('#'+formid).serialize() + '&mode=ajax', //&mode=ajax is my custom data
            success:function(response){             
    
                    console.log(response);
                            alert(response.message);
    
            },
            timeout:10000
    });
    

    在views.py中:

            data = {'error': '0', 'message': 'all was ok'}
            return HttpResponse(json.dumps(data), mimetype="application/json")
    

    以上内容应该适合您。我的测试是使用 Django 1.6 和 Python 2.7.5

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2016-06-25
      • 1970-01-01
      • 2023-03-05
      • 2012-11-03
      相关资源
      最近更新 更多