【问题标题】:Upload file using jQuery ajax with Django使用 jQuery ajax 和 Django 上传文件
【发布时间】:2021-03-16 13:43:38
【问题描述】:

我正在使用 Django 学习 ajax 和 JQuery。我创建了一个基本应用程序来更新文本字段,但现在我添加了文件字段。但无法使其工作。

is 模型类

class TextModel(models.Model):
    text=models.CharField(max_length=200)
    file=models.FileField(upload_to='files')

这是我的模板

<div class='col-8 mt-5'>
    <form method='POST' id='formCreated' data-url="{% url 'home' %}" enctype="multipart/form-data">
        <!-- data-url is used in ajax function -->
        {% csrf_token %}
        {{ form.as_p }}
        <button type="button" id="btn_submit">Upload</button> 
    </form>
    </div>
    
    <div class='col-5 mt-5' id='resultid'> 
    </div>

这是我的意见功能

def home(request):
    if request.method=='POST':
        form = TextForm(request.POST,request.FILES)
        if form.is_valid():
            out=form.save()
            return JsonResponse({'text':model_to_dict(out)},status=200)
        else:
            return render(request,'home.html',{'form':form})
    else:
        form = TextForm()
        return render(request,'home.html',{'form':form})

这是我在 js 文件中的代码

$(document).ready(function(){

    $('#btn_submit').click(function()
    {
        var serializedData=$('#formCreated').serialize();
        console.log(serializedData)


        $.ajax({
            url:$("formCreated").data('url'),
            data:serializedData,
            type:'POST',
            success:function(response){
                // reponse recieved from views recieved here and sent to div with resultid in home.html
                console.log(response)
                $('#resultid').append(response.text.text)
                // first text is key of response and second text is the text object
            }
        })

        $('#formCreated')[0].reset();
    });

});

这是我遇到的错误

file.js:16 Uncaught TypeError: Cannot read property 'text' of undefined
    at Object.success (file.js:16)
    at c (jquery.min.js:3)
    at Object.fireWith [as resolveWith] (jquery.min.js:3)
    at k (jquery.min.js:5)
    at XMLHttpRequest.r (jquery.min.js:5)

file.js 是上面js 代码所在的文件。

【问题讨论】:

    标签: javascript jquery django ajax


    【解决方案1】:

    这是我发现的解决方案

    $(document).ready(function(){
        $('#btn_submit').click(function()
        {
            console.log('button clicked')
            var form = $('#formCreated');
            var formdata = false;
            if (window.FormData){
                formdata = new FormData(form[0]);
            }
            var formAction = form.attr('action');
            $.ajax({
                url         : $("formCreated").data('url'),
                data        : formdata ? formdata : form.serialize(),
                cache       : false,
                contentType : false,
                processData : false,
                type        : 'POST',
                success:function(response){
                    // reponse recieved from views recieved here and sent to div with resultid in home.html
                    console.log(response)
                    $('#resultid').append(response.text)
                    // first text is key of response and second text is the text object
                
                }
            });
        });
    
    })
    

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 2013-03-26
      • 2014-01-16
      • 2011-11-01
      • 2015-03-23
      • 1970-01-01
      • 2012-12-05
      • 2015-04-04
      • 2019-03-25
      相关资源
      最近更新 更多