1. 程式人生 > >ajax 上傳檔案,post上傳檔案,ajax 提交 JSON 格式的資料

ajax 上傳檔案,post上傳檔案,ajax 提交 JSON 格式的資料

ajax簡介

前後臺做資料互動

前後端做資料互動的方式(三種):    

(1)瀏覽器視窗輸入地址(get的方式)
(2)form表單提交資料
(3)ajax提交資料

特點

特點:
  (
1)非同步       非同步與同步的區別:同步是請求發過去,要等著迴應;非同步不需要等待,可以進行其他操作   (2)區域性重新整理

使用

使用:
        (1)url:匹配的路由
        (2)type:傳送的的方式
        (3)data:傳送的資料
        (4)success:傳送的資料成功回撥條數

         $(
'.btn').click(function () { $.ajax({ url:'/index/', type:'post', data:{"name":'lqz',"age":18}, success:function (data) { alert(data) } }) }); 前端知識點: $(
'#id') : JQ獲取標籤 $('#id').val() : 獲取值 js跳轉頁面:location.href = 'https://www.baidu.com/'

post 上傳檔案

 知識要點:
        (1)enctype="multipart/form-data"  傳檔案格式
        (2)enctype="application/x-www-form-urlencoded"   預設格式

    (1)post上傳檔案
        模板層:
            <form action="/myfiles/
" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"> <input type="submit" value="提交"> </form> 檢視層: def myfiles(request): if request.method == 'GET': return render(request, 'myfiles.html') files = request.FILES 拿到字典 {'myfile': [<InMemoryUploadedFile: 111.png (image/png)>]}> my_file = files.get('myfile') with open(my_file.name,'wb') as f: for i in my_file: f.write(i) return HttpResponse('OK')