一、iframe使用
iframe在一个页面中,相当于整个window窗口的子窗口,可通过页面的元素结构查看。
<div> <p>学习iframe</p> <form id='form' action="ajax1" method="post" target="ifra"> <input type="text"> <input type="button" value="提交" class="btn" onclick="ajaxSubmit5()"> </form> <iframe id="iframe" name="ifra" style="height: 100px; 250px;" ></iframe> </div> …… function ajaxSubmit5() { document.getElementById('iframe').onload = reloadIframe; $('#form').submit(); } function reloadIframe() { //ret = this.contentWindow.document.body.innerText ret = $(this).contents().find('body').text() data = JSON.parse(ret) if (data.status == 'success') alert('welcome') }
def ajax1(request): print(request.GET) print(request.POST) print(request.body) ret = {'status':'success','data':[1,'hello']} return HttpResponse(json.dumps(ret))
执行过程:
①在输入框输入内容并点击提交,执行ajaxSubmit5(),并通过submit()向后台提交数据;
②由于在form表单中设置了target="ifra",即target为iframe的name值,因此后台HttpResponse的返回值传递给iframe
③后台向iframe传递返回值时,即onload触发reloadIframe()
④在reloadIframe()中,通过this.contentWindow.document.body.innerText获取iframe的显示内容,即HttpResponse的返回值,再进行判断。
二、利用iframe+form上传文件
<form id='form1' action="ajax1" method="post" target="ifra1" enctype="multipart/form-data"> <input type="text" name="k1"> <input type="text" name="k2"> <input type="file" name="k3"> <input type="button" value="提交" class="btn" onclick="ajaxSubmit8()"> </form> <iframe id="iframe1" name="ifra1" style="display: none;"></iframe>
function ajaxSubmit8() { $('#form1').submit(); document.getElementById('iframe1').onload = reloadIframe1; } function reloadIframe1() { ret = this.contentWindow.document.body.innerHTML data = JSON.parse(ret) if (data.status == 'success') alert('welcome') }
def ajax1(request): print(request.POST) print(request.FILES) obj = request.FILES.get('k3') file_path = os.path.join('static', obj.name) with open(file_path, 'wb') as f: for line in obj.chunks(): f.write(line) ret = {'status':'success','data':[1,'hello']} return HttpResponse(json.dumps(ret))
三、利用ajax+FormData上传文件
<input type="file" id="img"> <input type="button" class="btn" value="提交" onclick="ajaxSubmit6()"> <input type="button" class="btn" value="提交" onclick="ajaxSubmit7()"> ……
function ajaxSubmit6() { var data = new FormData() //使用FormData时,需要在ajax中添加processData和contentType两个参数 data.append('k1','v1') data.append('k2','v2') f = $('#img')[0].files[0] data.append('k3',f) $.ajax({ url:'ajax1', type:'POST', data:data, processData:false, contentType:false, success:function (arg) { console.log(arg) } }) } function ajaxSubmit7() { var data = new FormData() //使用FormData来传递数据时,无论是使用jQuery还是原生的XMLHttpRequest,都不能在后台使用request.body,数据在request.POST和request.FILES中 data.append('k1','v1') data.append('k2','v2') f = $('#img')[0].files[0] data.append('k3',f) var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4) console.log(xhr.responseText); } xhr.open('POST','ajax1'); xhr.send(data); }
def ajax1(request): print(request.POST) print(request.FILES) obj = request.FILES.get('k3') file_path = os.path.join('static', obj.name) with open(file_path, 'wb') as f: for line in obj.chunks(): f.write(line) ret = {'status':'success','data':[1,'hello']} return HttpResponse(json.dumps(ret))
四、利用iframe+form上传并生成图片预览
<form id='form1' action="upload_file" method="post" target="ifra1" enctype="multipart/form-data"> <input type="file" name="k3" onchange="uploadFile()"> </form> <iframe id="iframe1" name="ifra1" style="display: none;"></iframe> <div>预览</div> <div id="preview"></div>
def upload_file(req): if req.method == 'GET': return render(req,'upload.html') else: ret = {'status': True, 'data': None, 'message': None} obj = req.FILES.get('k3') nid = str(uuid.uuid4()) file_path = os.path.join('static', nid + obj.name) with open(file_path, 'wb') as f: for line in obj.chunks(): f.write(line) ret['data'] = file_path return HttpResponse(json.dumps(ret))
<script src="/static/jquery-3.3.1.min.js"></script> <script> function uploadFile() { document.getElementById('iframe1').onload = reloadIframe1; $('#form1').submit(); } function reloadIframe1() { ret = this.contentWindow.document.body.innerHTML obj = JSON.parse(ret) console.log(obj) var tag = document.createElement('img') //创建img标签 tag.src = obj.data //设置img标签的src为本地已上传图片的路径 $('#preview').empty().append(tag) //清空预览图片并上传新的图片 } </script>