Ajax

Ajax

 contentType参数:告诉服务器知道这次请求的数据格式
 contentType: "application/x-www-form-urlencoded" :'user=alex&pwd=123'
               "application/json": json字符串,'{"user":"alex","pwd":"123"}'
 csrf跨域:
    
         方式1:"csrfmiddlewaretoken":$("[name='csrfmiddlewaretoken']").val();
         方式2: $.ajax({headers:{"X-CSRFToken":$.cookie('csrftoken')},})
    
$("#myForm").serialize():form表单中input标签比较多,需要传多对键值对到后端,
而该方法就可以将form中所有的键值对传回后端。

用form表单上传文件

建立url与views之间的联系

url:
from django.conf.urls import url
from app01 import views

urlpatterns = [
    url(r'^index/', views.index),]

views:
 import os
 from filePut import settings
from django.shortcuts import render,HttpResponse
def index(request): 
file_obj
=request.FILES.get("cFile")
   name=file_obj.name
path
=os.path.join(settings.BASE_DIR,"app01","static",name)
with open(path,
"wb") as f_write:
    for line in file_obj:
      f_write.write(line)
return render(request,"index.html") 新建index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="/index/" method="post" enctype="multipart/form-data">
     {% csrf_token %}
    <p>姓名: <input type="text" name="user"></p>
    <p>文件: <input type="file" name="cFile"></p>
    <input type="submit">
</form>
</body>
</html>
index.html

 用ajax上传文件

建立url与views的联系

url:
from django.conf.urls import url
from app01 import views

urlpatterns = [
    url(r'^indexAjax/', views.indexAjax),
]


views:
 import os
 from filePut import settings
from django.shortcuts import render,HttpResponse
def indexAjax(request): 
file_obj=request.FILES.get("cFile")
name=file_obj.name
path=os.path.join(settings.BASE_DIR,"app01","static",name)
with open(path,"wb") as f_write:
    for line in file_obj:
      f_write.write(line)
return
HttpResponse("123421")

新建index.html文件

方式1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
</head>
<body>

    {% csrf_token %}
    <p>姓名: <input type="text" id="user"></p>
    <p>文件: <input type="file" id="cFile"></p>
    <input type="button" value="submit">


<script>
    $(":button").click(function () {
          var $formData=new FormData() ;
          $formData.append("user",$("#user").val());
          $formData.append("cFile",$("#cFile")[0].files[0]);



        $.ajax({
            url:"/indexAjax/",
            type:"post",
            data:{
                 $formData
            },
            contentType:false,
            processData:false,    // 不对数据做预处理,不进行任何编发
            headers:{"X-CSRFToken":$('[name="csrfmiddlewaretoken"]').val()},
            success:function (data) {
                console.log(data)
            }
        })

    })
</script>




</body>
</html>



方式2:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
</head>
<body>


    {% csrf_token %}
    <p>姓名: <input type="text" id="user"></p>
    <p>文件: <input type="file" id="cFile"></p>
    <input type="button" value="submit">


<script>
    $(":button").click(function () {
        $.ajax({
            url:"/indexAjax/",
            type:"post",
            data:{
                cf:$("#cFile")[0].files[0]
            },
            contentType:"application/json",
            headers:{"X-CSRFToken":$('[name="csrfmiddlewaretoken"]').val()},
            success:function (data) {
                console.log(data)
            }
        })

    })
</script>




</body>
</html>
index.html

 

posted @ 2018-01-10 20:06  星雨5213  阅读(86)  评论(0)    收藏  举报