【问题标题】:Django/Ajax sending 'none' value to viewDjango/Ajax 发送“无”值来查看
【发布时间】:2021-08-11 16:09:56
【问题描述】:

当我从 ajax 发送数据以在 Django 中查看时,我没有得到任何数据。似乎是什么问题。这是我的代码。好像我删除了processData:false,contentType:false,然后数据打印成功,但在文件上却给出错误。

Ajax 代码

<script>
  function submit_data()
  {
    var type = $('#type').val();
    var subtype = $('#subtype').val();
    var name = $('#name').val();
    var price = $('#price').val();
    var weight = $('#weight').val();
    var details = $('#details').val();
    var picture1 = $('#image1')[0].files[0];
    var picture2 = $('#image2')[0].files[0];
    var picture3 = $('#image3')[0].files[0];
    var vedio_url = $('#vedio_link').val();
    alert(picture1)

    $.ajax({
        url: '/add_record/',
        type: 'POST',
        headers: { "X-CSRFToken": '{{csrf_token}}' },
        processData: false,
        contentType: false,
        data: {
          type,
          subtype,
          name,
          price,
          weight,
          details,
          picture1,
          picture2,
          picture3,
          vedio_url,
        },
        success: function (response) {
          alert("datauploaded successfully!")
        },
         error: function(){
            alert('error')
        }
      });
  }


</script>

查看代码

def add_record(request):
    print("Yes i am here")
    type = request.POST.get('type')
    subtype = request.POST.get('subtype')
    name = request.POST.get('name')
    price = request.POST.get('price')
    weight = request.POST.get('weight')
    details = request.POST.get('details')
    picture1 = request.FILES.get('picture1')
    picture2 = request.FILES.get('picture2')
    picture3 = request.FILES.get('picture3')
    vedi_url = request.POST.get('vedio_url')
    print (picture1)
    print(type)
    print(request.POST)
    return JsonResponse({'message':'success'},status=200)

错误:

Yes i am here
None
None
<QueryDict: {}>

它没有返回,这是为什么呢?

【问题讨论】:

    标签: django ajax django-views


    【解决方案1】:

    没有文件的 Ajax:

    你的 JS data 元素应该是一个字典,同时删除 processDatacontentType 参数。

    <!doctype html>
    <html lang="en">
    <head>
    </head>
    <body>
        <input type="text" id="name"/>
        <button type="button" id="send" onclick="submit_data()">Send<button/>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <script>
        function submit_data()
        {
            var name = $('#name').val();
            $.ajax({
                url: '/add_record/',
                type: 'POST',
                headers: { "X-CSRFToken": '{{csrf_token}}' },
                data: {
                'name': name,
                },
                success: function (response) {
                alert(response.data)
                },
                error: function(){
                    alert('error')
                }
            });
        }
        </script>
    </body>
    </html>
    

    观看次数:

    from django.shortcuts import render
    from django.http import JsonResponse
    
    
    def form_record(request):
        return render(request, "mytemplate.html", {})
    
    def add_record(request):
        print("Yes i am here")
        name = request.POST.get('name')
        print(f"Post: {request.POST}")
        return JsonResponse({'data': name},status=200)
    

    带有文件的 Ajax:

    因为您要发送二进制数据,所以您应该使用FormData

        function submit_data()
        {
            var name = $('#name').val();
            var formData = new FormData()  // changes here
            formData.append('name', name)  // and here
            $.ajax({
                url: '/add_record/',
                type: 'POST',
                headers: { "X-CSRFToken": '{{csrf_token}}' },
                contentType: false,   // and here
                enctype: 'multipart/form-data',  // and here
                processData: false,  // and here
                cache: false,
                data: formData,  // <-- carefully here
                success: function (response) {
                alert(response.data)
                },
                error: function(){
                    alert('error')
                }
            });
        }
    

    结果:

    【讨论】:

    • 另外,您应该删除contentType 参数:当数据作为字符串传递时,它应该已经使用正确的 contentType 编码进行编码,默认情况下是 application/x-www-表单-urlencoded。
    • 当我删除 '''contentType''' 参数时,输出是。 '''是的,我在这里 无 无 '''
    • 如果我同时删除参数“contenttype”和“processData”参数,则会出现错误。 “TypeError:无法在‘Blob’上执行‘arrayBuffer’:非法调用”。
    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 2017-04-29
    • 2014-06-21
    • 2017-10-07
    • 2019-11-10
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    相关资源
    最近更新 更多