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

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。Ajax上传数据和上传文件(三种方式),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

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

三种方式传递数据和上传文件HTML页面

<!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>Title</title>
     <style>
         .btn {
             background-color: coral;
             color: white;
             padding: 5px 10px;
             border-radius: 26%;
             cursor: pointer;
         }
     </style>
 </head>
 <body>
 <h1>原生Ajax测试</h1>
 <a class="btn" onclick="AjaxTest1()">get发送</a>  <a class="btn" onclick="AjaxTest2()">post发送</a>
 
 <h1>仿Ajax(iframe+form)测试</h1>
 <iframe src="" frameborder="1" id="ifm" name="ifm"></iframe>
 <form action="/ajax" method="get" target="ifm" id="fm">
     <p><input type="text" name="user"></p>
     <p><a onclick="AjaxTest4()">提交</a></p>
     {% comment %}    <p><input type="submit" value="提交"></p>{% endcomment %}
 </form>
 
 <h1>上传文件</h1>
 <h3>Ajax(jQuery+原生)上传</h3>
 <p><input type="file" id="file"></p>
 <a class="btn" onclick="AjaxTest5()">上传</a>
 
 <h3>Ajax(iframe+form)上传</h3>
 <iframe src="" frameborder="1" id="ifm2" name="ifm2"></iframe>
 <form action="/ajax" method="post" target="ifm2" enctype="multipart/form-data" id="fm2">
     <p><input type="file" id="if_file" name="k3"></p>
     <a class="btn" onclick="AjaxTest6()">上传</a>
 </form>
 
 
 <script>
     function AjaxTest1() {
         var xhr = new XMLHttpRequest();
         xhr.onreadystatechange = function () {
             if (xhr.readyState == 4) {
                 console.log(xhr.responseText);
             }
         };
         xhr.open("GET", "/ajax?p=123");
         xhr.send(null);
     }
 
     function AjaxTest2() {
         var xhr = new XMLHttpRequest();
         xhr.onreadystatechange = function () {
             if (xhr.readyState == 4) {
                 console.log(xhr.responseText);
             }
         };
         xhr.open("POST", "/ajax");
         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset-UTF-8");
         xhr.send("p=222");
     }
 
     function AjaxTest4() {
         document.getElementById("ifm").onload = AjaxTest3;
         document.getElementById("fm").submit();
     }
 
     function AjaxTest3() {
         {#console.log(thi.contentWindow.document.body.innerText);#}
         {#console.log($(thi).contents().find("body").html());#}
         var content = this.contentWindow.document.body.innerHTML;
         var obj = JSON.parse(content);
         if (obj.status) {
             alert(obj.message);
         }
     }
 
     function AjaxTest5() {
         var formdata = new FormData()
         formdata.append("k1", "v1");
         formdata.append("k2", "v2");
         formdata.append("k3", document.getElementById("file").files[0]);
         var xhr = new XMLHttpRequest();
         xhr.onreadystatechange = function () {
             if (xhr.readyState == 4) {
                 console.log(xhr.responseText);
             }
         };
         xhr.open("POST", "/ajax");
         {#xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset-UTF-8");#}
         xhr.send(formdata);
     }
 
     function AjaxTest6() {
         document.getElementById("ifm2").onload = AjaxTest7;
         document.getElementById("fm2").submit();
     }
 
     function AjaxTest7() {
         {#console.log(thi.contentWindow.document.body.innerText);#}
         {#console.log($(thi).contents().find("body").html());#}
         var content = this.contentWindow.document.body.innerHTML;
         var obj = JSON.parse(content);
         console.log(obj);
     }
 </script>
 </body>

后端view函数接收数据

from django.shortcuts import render,HttpResponse,redirect
import uuid
import os
import json

# Create your views here.
def ajax(request):
    print("get请求:",request.GET)
    print("post请求:",request.POST)
    # print("请求体:",request.body)
    print(request.FILES)
    ret={'status':True,'message':'ok!'}
    file=request.FILES.get("k3")
    f=open(file.name,"wb")
    for i in file.chunks():
        f.write(i);
    f.close()

    return HttpResponse(json.dumps(ret))

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

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

上传图片并在上传页面展示HTML页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<iframe src="" frameborder="1" id="ifm" name="ifm" style="display: none"></iframe>
<form action="/upload" method="post" enctype="multipart/form-data" id="fm" target="ifm">
    <p><input type="file" onchange="upload()" name="img"></p>
</form>
<h3>预览</h3>
<div id="preview">

</div>
<script src="/static/jquery-1.11.0.js"></script>
<script>
    function upload() {
        document.getElementById("ifm").onload = uploadifm;
        document.getElementById("fm").submit();
    }

    function uploadifm() {
        var content = this.contentWindow.document.body.innerHTML;
        var obj = JSON.parse(content);
        var tag = document.createElement("img");
        tag.src = obj.path;
        $("#preview").empty().append(tag);
    }
</script>
</body>
</html>

上传图片并在上传页面展示后端view函数

from django.shortcuts import render,HttpResponse,redirect
import uuid
import os
import json

# Create your views here.

def upload(request):
    if request.method=="GET":
        return render(request,"upload.html")
    else:
        dic={'status':True,'path':None,'message':None}
        img=request.FILES.get("img")
        uid=str(uuid.uuid4())
        file_path=os.path.join("static",uid+img.name)
        f=open(file_path,"wb")
        for i in img.chunks():
            f.write(i)
        f.close()
        dic["path"]=file_path
        dic["message"]="上传成功!"
        return HttpResponse(json.dumps(dic))

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/187768.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!