JQuery ajax 上传

上传数据

发送

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax</title>
</head>
<body>

<form>
    <label for="username">账号</label>
    <input id="username" type="text">
    <label for="password">密码</label>
    <input id="password" type="password">
</form>
<button class="btn">提交</button>

<script src="/static/jquery.js"></script>
<script>
    $('.btn').click(function () {
        var username = $('#username').val();
        var password = $('#password').val();
        $.ajax({
            url:'/info',
            type:'post',
            data:{'username':username,'password':password},
            success:function () {
                alert('成功')
            },
            error:function () {
                alert('失败')
            }
        })
    })
</script>
</body>
</html>

接收

from django.shortcuts import render

# Create your views here.

def index(request):
    return render(request,'index.html')

def info(request):
    if request.method == "POST":
        print(request.POST)
        return render(request,'info.html')

结果

上传文件

发送

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax</title>
</head>
<body>

<form id="form-upload" enctype="multipart/form-data">
    <input id="picture" type="file" name="picture">
    <!-- 上传多文件,添加multiple -->
    <!-- <input id="picture" type="file" name="picture" multiple="multiple"> -->
</form>
<button class="btn">上传</button>

<script src="/static/jquery.js"></script>
<script>
    $('.btn').click(function () {
        var formData = new FormData(); // 可以传一个form
        var picture = $('#picture')[0].files[0]; // 获取文件对象
        formData.append('picture',picture); // 图片
        formData.append('name','kidd'); // 字符串
        $.ajax({
            url:'/upload',
            type:'post',
            data:formData,
            cache: false,
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType : false, // 告诉jQuery不要去设置Content-Type请求头
            success:function () {
                alert('成功')
            },
            error:function () {
                alert('失败')
            }
        })
    })
</script>
</body>
</html>

接收

from django.shortcuts import render,HttpResponse

def upload(request):
    if request.method == 'GET':
        return render(request,'upload.html')

    if request.method == "POST":
        name = request.POST.get('name')
        picture = request.FILES.get('picture')
        if picture:
            path = 'static/%s'%picture.name
            with open(path,'wb') as f:
                for chunk in picture.chunks(): # 文件小的话,可以直接读取,使用read()
                    f.write(chunk)

        return HttpResponse('')

注意

let fo = document.queryselect('form')
let formData = new FormData(fo)
console.log(formData)  //这样输出,formData里面是没有数据的
以为在控制台中访问不到formData的数据,你在控制台看到的是FormData原型,存储的数据没有以对象属性的方式体现,可以理解为类的私有字段,外界访问不到,但是你可以通过formData.get("name")的方式获取到对应的表单数据。
还有千万不要写错字,例如:formData。如果报错文件是发不出去的。

猜你喜欢

转载自www.cnblogs.com/py-peng/p/12643903.html