亲宝软件园·资讯

展开

Ajax上传数据和上传文件(三种方式)

孙小龙 人气:0

Ajax向后端发送数据可以有三种方式:原生Ajax方式,jQuery Ajax方式,iframe+form 方式(伪造Ajax方式)

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <style>
  7         .btn {
  8             background-color: coral;
  9             color: white;
 10             padding: 5px 10px;
 11             border-radius: 26%;
 12             cursor: pointer;
 13         }
 14     </style>
 15 </head>
 16 <body>
 17 <h1>原生Ajax测试</h1>
 18 <a class="btn" onclick="AjaxTest1()">get发送</a>&nbsp;&nbsp;<a class="btn" onclick="AjaxTest2()">post发送</a>
 19 
 20 <h1>仿Ajax(iframe+form)测试</h1>
 21 <iframe src="" frameborder="1" id="ifm" name="ifm"></iframe>
 22 <form action="/ajax" method="get" target="ifm" id="fm">
 23     <p><input type="text" name="user"></p>
 24     <p><a onclick="AjaxTest4()">提交</a></p>
 25     {% comment %}    <p><input type="submit" value="提交"></p>{% endcomment %}
 26 </form>
 27 
 28 <h1>上传文件</h1>
 29 <h3>Ajax(jQuery+原生)上传</h3>
 30 <p><input type="file" id="file"></p>
 31 <a class="btn" onclick="AjaxTest5()">上传</a>
 32 
 33 <h3>Ajax(iframe+form)上传</h3>
 34 <iframe src="" frameborder="1" id="ifm2" name="ifm2"></iframe>
 35 <form action="/ajax" method="post" target="ifm2" enctype="multipart/form-data" id="fm2">
 36     <p><input type="file" id="if_file" name="k3"></p>
 37     <a class="btn" onclick="AjaxTest6()">上传</a>
 38 </form>
 39 
 40 
 41 <script>
 42     function AjaxTest1() {
 43         var xhr = new XMLHttpRequest();
 44         xhr.onreadystatechange = function () {
 45             if (xhr.readyState == 4) {
 46                 console.log(xhr.responseText);
 47             }
 48         };
 49         xhr.open("GET", "/ajax?p=123");
 50         xhr.send(null);
 51     }
 52 
 53     function AjaxTest2() {
 54         var xhr = new XMLHttpRequest();
 55         xhr.onreadystatechange = function () {
 56             if (xhr.readyState == 4) {
 57                 console.log(xhr.responseText);
 58             }
 59         };
 60         xhr.open("POST", "/ajax");
 61         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset-UTF-8");
 62         xhr.send("p=222");
 63     }
 64 
 65     function AjaxTest4() {
 66         document.getElementById("ifm").onload = AjaxTest3;
 67         document.getElementById("fm").submit();
 68     }
 69 
 70     function AjaxTest3() {
 71         {#console.log(thi.contentWindow.document.body.innerText);#}
 72         {#console.log($(thi).contents().find("body").html());#}
 73         var content = this.contentWindow.document.body.innerHTML;
 74         var obj = JSON.parse(content);
 75         if (obj.status) {
 76             alert(obj.message);
 77         }
 78     }
 79 
 80     function AjaxTest5() {
 81         var formdata = new FormData()
 82         formdata.append("k1", "v1");
 83         formdata.append("k2", "v2");
 84         formdata.append("k3", document.getElementById("file").files[0]);
 85         var xhr = new XMLHttpRequest();
 86         xhr.onreadystatechange = function () {
 87             if (xhr.readyState == 4) {
 88                 console.log(xhr.responseText);
 89             }
 90         };
 91         xhr.open("POST", "/ajax");
 92         {#xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset-UTF-8");#}
 93         xhr.send(formdata);
 94     }
 95 
 96     function AjaxTest6() {
 97         document.getElementById("ifm2").onload = AjaxTest7;
 98         document.getElementById("fm2").submit();
 99     }
100 
101     function AjaxTest7() {
102         {#console.log(thi.contentWindow.document.body.innerText);#}
103         {#console.log($(thi).contents().find("body").html());#}
104         var content = this.contentWindow.document.body.innerHTML;
105         var obj = JSON.parse(content);
106         console.log(obj);
107     }
108 </script>
109 </body>
三种方式传递数据和上传文件HTML页面
 1 from django.shortcuts import render,HttpResponse,redirect
 2 import uuid
 3 import os
 4 import json
 5 
 6 # Create your views here.
 7 def ajax(request):
 8     print("get请求:",request.GET)
 9     print("post请求:",request.POST)
10     # print("请求体:",request.body)
11     print(request.FILES)
12     ret={'status':True,'message':'ok!'}
13     file=request.FILES.get("k3")
14     f=open(file.name,"wb")
15     for i in file.chunks():
16         f.write(i);
17     f.close()
18 
19     return HttpResponse(json.dumps(ret))
20 
21 def index(request):
22     return render(request,"index.html")
后端view函数接收数据

模拟网站上传图片并在网页实时显示图片效果

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <iframe src="" frameborder="1" id="ifm" name="ifm" style="display: none"></iframe>
 9 <form action="/upload" method="post" enctype="multipart/form-data" id="fm" target="ifm">
10     <p><input type="file" onchange="upload()" name="img"></p>
11 </form>
12 <h3>预览</h3>
13 <div id="preview">
14 
15 </div>
16 <script src="/static/jquery-1.11.0.js"></script>
17 <script>
18     function upload() {
19         document.getElementById("ifm").onload = uploadifm;
20         document.getElementById("fm").submit();
21     }
22 
23     function uploadifm() {
24         var content = this.contentWindow.document.body.innerHTML;
25         var obj = JSON.parse(content);
26         var tag = document.createElement("img");
27         tag.src = obj.path;
28         $("#preview").empty().append(tag);
29     }
30 </script>
31 </body>
32 </html>
上传图片并在上传页面展示HTML页面
 1 from django.shortcuts import render,HttpResponse,redirect
 2 import uuid
 3 import os
 4 import json
 5 
 6 # Create your views here.
 7 
 8 def upload(request):
 9     if request.method=="GET":
10         return render(request,"upload.html")
11     else:
12         dic={'status':True,'path':None,'message':None}
13         img=request.FILES.get("img")
14         uid=str(uuid.uuid4())
15         file_path=os.path.join("static",uid+img.name)
16         f=open(file_path,"wb")
17         for i in img.chunks():
18             f.write(i)
19         f.close()
20         dic["path"]=file_path
21         dic["message"]="上传成功!"
22         return HttpResponse(json.dumps(dic))
上传图片并在上传页面展示后端view函数

 

加载全部内容

相关教程
猜你喜欢
用户评论