1.ajax
概述:
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新,而传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
1.1 原生Ajax
原生Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。
XmlHttpRequest对象的主要方法:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
a. void open(String method,String url,Boolen async) 用于创建请求 参数: method: 请求方式(字符串类型),如:POST、GET、DELETE... url: 要请求的地址(字符串类型) async: 是否异步(布尔类型) b. void send(String body) 用于发送请求 参数: body: 要发送的数据(字符串类型) c. void setRequestHeader(String header,String value) 用于设置请求头 参数: header: 请求头的key(字符串类型) vlaue: 请求头的value(字符串类型) d. String getAllResponseHeaders() 获取所有响应头 返回值: 响应头数据(字符串类型) e. String getResponseHeader(String header) 获取响应头中指定header的值 参数: header: 响应头的key(字符串类型) 返回值: 响应头中指定的header对应的值 f. void abort() 终止请求 |
XmlHttpRequest对象的主要属性:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
a. Number readyState 状态值(整数) 详细: 0-未初始化,尚未调用open()方法; 1-启动,调用了open()方法,未调用send()方法; 2-发送,已经调用了send()方法,未接收到响应; 3-接收,已经接收到部分响应数据; 4-完成,已经接收到全部响应数据; b. Function onreadystatechange 当readyState的值改变时自动触发执行其对应的函数(回调函数) c. String responseText 服务器返回的数据(字符串类型) d. XmlDocument responseXML 服务器返回的数据(Xml对象) e. Number states 状态码(整数),如:200、404... f. String statesText 状态文本(字符串),如:OK、NotFound... |
基于原生AJAX案例:
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^ajax/', views.ajax),
url(r'^json/', views.json),
]
project/urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^ajax/', views.ajax),
url(r'^json/', views.json),
]
def ajax(request):
return render(request,'ajax.html')
def json(requset):
ret = {'status':True,'data':None)}
import json
return HttpResponse(json.dumps(ret))
app01/views.py
def ajax(request):
return render(request,'ajax.html')
def json(requset):
ret = {'status':True,'data':None)}
import json
return HttpResponse(json.dumps(ret))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text"/>
<input type="button" value="Ajax1" onclick="Ajax1();"/>
<script src="/static/jquery-1.12.4.js/"></script>
<script>
//跨浏览器支持
function getXHR(){
var xhr = null;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function Ajax1() {
var xhr = new getXHR();
xhr.open('POST','/json/',true);
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
//接收完毕,执行以下操作
//console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
// 设置请求头,后端输入print(requset.POST),可获取send数据
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
//只能是字符串格式
xhr.send("name=root;pwd=123")
}
</script>
</body>
</html>
templates/ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text"/>
<input type="button" value="Ajax1" onclick="Ajax1();"/>
<script src="/static/jquery-1.12.4.js/"></script>
<script>
//跨浏览器支持
function getXHR(){
var xhr = null;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function Ajax1() {
var xhr = new getXHR();
xhr.open('POST','/json/',true);
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
//接收完毕,执行以下操作
//console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
// 设置请求头,后端输入print(requset.POST),可获取send数据
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
//只能是字符串格式
xhr.send("name=root;pwd=123")
}
</script>
</body>
</html>
1.2 ajax jquery
jQuery其实就是一个JavaScript的类库(JS框架),其将复杂的功能做了上层封装,使得开发者可以在其基础上写更少的代码实现更多的功能。
- jQuery 不是生产者,而是大自然搬运工。
- jQuery Ajax本质 XMLHttpRequest 或 ActiveXObject
jQuery Ajax 方法列表:
基于jQueryAjax-demo
1.3 “伪”AJAX
由于HTML标签的iframe标签具有局部加载内容的特性,所以可以使用其来伪造Ajax请求。
① Form表单提交到iframe中,页面不刷新
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title></head><body> <input type="text"/> <input type="button" value="Ajax1" onclick="Ajax1();" /> <form action="/ajax_json/" method="POST" target="ifm1"> <!-- target跟iframe进行关联 --> <iframe id="ifm1" name="ifm1" ></iframe> <input type="text" name="username" /> <input type="text" name="email" /> <input type="submit" value="Form提交"/> </form></body></html>②.Ajax提交到iframe中,页面不刷新 |
② Ajax提交到iframe中,页面不刷新
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title></head><body> <input type="text"/> <input type="button" value="Ajax1" onclick="Ajax1();" /> <input type='text' id="url" /> <input type="button" value="发送Iframe请求" onclick="iframeRequest();" /> <iframe id="ifm" src="http://www.baidu.com"></iframe> <script src="/static/jquery-1.12.4.js"></script> <script> function iframeRequest(){ var url = $('#url').val(); $('#ifm').attr('src',url); } </script></body></html>③.Form表单提交到iframe中,并拿到iframe中的数据 |
③ Form表单提交到iframe中,并拿到iframe中的数据
2.上传文件
2.1 Form表单上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user"/>
<input type="file" name="img"/>
<input type="submit" value="提交">
</form>
</body>
</html>
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user"/>
<input type="file" name="img"/>
<input type="submit" value="提交">
</form>
</body>
</html>
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.
def upload(request):
if request.method == "GET":
return render(request,'upload.html')
else:
user = request.POST.get('user')
img = request.FILES.get('img')
#img是个对象(文件大小,文件名称,文件内容...)
print(img.name)
print(img.size)
n = open(img.name,'wb')
for i in img.chunks():
n.write(i)
n.close()
return HttpResponse('...!')
python
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.
def upload(request):
if request.method == "GET":
return render(request,'upload.html')
else:
user = request.POST.get('user')
img = request.FILES.get('img')
#img是个对象(文件大小,文件名称,文件内容...)
print(img.name)
print(img.size)
n = open(img.name,'wb')
for i in img.chunks():
n.write(i)
n.close()
return HttpResponse('...!')
伪装上传按钮样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user"/>
<div style="position: relative">
<a>上传图片</a>
<input type="file" name="img" style="opacity: 0.2;position:absolute;top: 0;left: 0" />
</div>
<input type="submit" value="提交">
</form>
</body>
</html>
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user"/>
<div style="position: relative">
<a>上传图片</a>
<input type="file" name="img" style="opacity: 0.2;position:absolute;top: 0;left: 0" />
</div>
<input type="submit" value="提交">
</form>
</body>
</html>

2.2 AJAX上传
基于原生Aja(XmlHttpRequest)上传文件
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^upload/$', views.upload),
url(r'^upload_file/$', views.upload_file),
]
project/urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^upload/$', views.upload),
url(r'^upload_file/$', views.upload_file),
]
def upload(request):
return render(request,'upload.html')
def upload_file(request):
username = request.POST.get('username')
send = request.FILES.get('send')
print(username,send)
with open(send.name,'wb') as f:
for item in send.chunks():
f.write(item)
ret = {'status': True, 'data': request.POST.get('username')}
import json
return HttpResponse(json.dumps(ret))
app01/views.py
def upload(request):
return render(request,'upload.html')
def upload_file(request):
username = request.POST.get('username')
send = request.FILES.get('send')
print(username,send)
with open(send.name,'wb') as f:
for item in send.chunks():
f.write(item)
ret = {'status': True, 'data': request.POST.get('username')}
import json
return HttpResponse(json.dumps(ret))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.upload{
display: inline-block;padding: 5px 10px;
background-color: dodgerblue;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom:0px;
z-index: 90;
}
.file{
100px;height: 50px;opacity: 0;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom:0px;
z-index: 100;
}
</style>
</head>
<body>
<div style="position: relative; 100px;height: 50px">
<input class="file" type="file" id="send" name="afafaf"/>
<a class="upload">上传</a>
</div>
<input type="button" value="提交xmlhttprequest" onclick="xhrSubmit();"/>
<script>
function xhrSubmit() {
//$('#send')[0]
var file_obj = document.getElementById('send').files[0];
var fd = new FormData();
fd.append('username','root');
fd.append('send',file_obj);
var xhr = new XMLHttpRequest();
xhr.open('POST','/upload_file/',true);
xhr.send(fd);
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
//接收完毕,执行以下操作
//console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
}
</script>
</body>
</html>
templates/upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.upload{
display: inline-block;padding: 5px 10px;
background-color: dodgerblue;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom:0px;
z-index: 90;
}
.file{
100px;height: 50px;opacity: 0;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom:0px;
z-index: 100;
}
</style>
</head>
<body>
<div style="position: relative; 100px;height: 50px">
<input class="file" type="file" id="send" name="afafaf"/>
<a class="upload">上传</a>
</div>
<input type="button" value="提交xmlhttprequest" onclick="xhrSubmit();"/>
<script>
function xhrSubmit() {
//$('#send')[0]
var file_obj = document.getElementById('send').files[0];
var fd = new FormData();
fd.append('username','root');
fd.append('send',file_obj);
var xhr = new XMLHttpRequest();
xhr.open('POST','/upload_file/',true);
xhr.send(fd);
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
//接收完毕,执行以下操作
//console.log(xhr.responseText);
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
}
</script>
</body>
</html>
基于Ajax JQuery进行文件的上传文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.upload{
display: inline-block;padding: 5px 10px;
background-color: dodgerblue;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom:0px;
z-index: 90;
}
.file{
100px;height: 50px;opacity: 0;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom:0px;
z-index: 100;
}
</style>
</head>
<body>
<div style="position: relative; 100px;height: 50px">
<input class="file" type="file" id="send" name="afafaf"/>
<a class="upload">上传</a>
</div>
<input type="button" value="提交jquery" onclick="jqSubmit();">
<script src="/static/jquery-1.12.4.js/"></script>
<script>
function jqSubmit(){
//$('#send')[0]
var file_obj = document.getElementById('send').files[0];
var fd = new FormData();
fd.append('username', 'root');
fd.append('send', file_obj);
$.ajax({
url: '/upload_file/',
type: 'POST',
data: fd,
processData:false,// tell jQuery not to process the data
contentType:false,// tell jQuery not to set contentType
success: function (arg, a1, a2) {
console.log(arg);
console.log(a1);
console.log(a2);
}
})
}
</script>
</body>
</html>
templates/upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.upload{
display: inline-block;padding: 5px 10px;
background-color: dodgerblue;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom:0px;
z-index: 90;
}
.file{
100px;height: 50px;opacity: 0;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom:0px;
z-index: 100;
}
</style>
</head>
<body>
<div style="position: relative; 100px;height: 50px">
<input class="file" type="file" id="send" name="afafaf"/>
<a class="upload">上传</a>
</div>
<input type="button" value="提交jquery" onclick="jqSubmit();">
<script src="/static/jquery-1.12.4.js/"></script>
<script>
function jqSubmit(){
//$('#send')[0]
var file_obj = document.getElementById('send').files[0];
var fd = new FormData();
fd.append('username', 'root');
fd.append('send', file_obj);
$.ajax({
url: '/upload_file/',
type: 'POST',
data: fd,
processData:false,// tell jQuery not to process the data
contentType:false,// tell jQuery not to set contentType
success: function (arg, a1, a2) {
console.log(arg);
console.log(a1);
console.log(a2);
}
})
}
</script>
</body>
</html>
Iframe进行文件的上传
def upload(request):
return render(request,'upload.html')
def upload_file(request):
username = request.POST.get('username')
send = request.FILES.get('send')
print(username, send)
import os
img_path = os.path.join('static/imgs/',send.name)
with open(img_path, 'wb') as f:
for item in send.chunks():
f.write(item)
ret = {'status': True, 'data': img_path}
import json
return HttpResponse(json.dumps(ret))
app01/views.py #上传到指定文件夹(static/imgs)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/upload_file/" enctype="multipart/form-data" target="ifm1">
<iframe id="iframe" name="ifm1" style="display: none"></iframe>
<input type="file" name="send"/>
<input type="submit" onclick="iframesubmit()" value="Form表单提交"/>
</form>
<script src="/static/jquery-1.12.4.js/"></script>
<script>
function iframesubmit() {
$("#iframe").load(function () {
var text = $('#iframe').contents().find('body').text();
var obj = JSON.parse(text);
console.log(obj);
})
}
</script>
</body>
</html>
3.图片预览
3.1上传图片后预览
def upload(request):
return render(request,'upload.html')
def upload_file(request):
username = request.POST.get('username')
send = request.FILES.get('send')
print(username, send)
import os
img_path = os.path.join('static/imgs/',send.name)
with open(img_path, 'wb') as f:
for item in send.chunks():
f.write(item)
ret = {'status': True, 'data': img_path}
import json
return HttpResponse(json.dumps(ret))
app01/views.py #上传到指定文件夹(static/imgs)
def upload(request):
return render(request,'upload.html')
def upload_file(request):
username = request.POST.get('username')
send = request.FILES.get('send')
print(username, send)
import os
img_path = os.path.join('static/imgs/',send.name)
with open(img_path, 'wb') as f:
for item in send.chunks():
f.write(item)
ret = {'status': True, 'data': img_path}
import json
return HttpResponse(json.dumps(ret))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
<iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
<input type="file" name="fafafa" />
<input type="submit" onclick="iframeSubmit();" value="Form提交"/>
</form>
<div id="preview"></div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
function iframeSubmit(){
$('#ifm1').load(function(){
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
console.log(obj)
//上传后增加预览模式
$('#preview').empty(); //清空原有相同文件
var imgTag = document.createElement('img'); //创建img标签
imgTag.src = "/" + obj.data; //路径
$('#preview').append(imgTag);
})
}
</script>
</body>
</html>
#HTML文件
templates/upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
<iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
<input type="file" name="fafafa" />
<input type="submit" onclick="iframeSubmit();" value="Form提交"/>
</form>
<div id="preview"></div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
function iframeSubmit(){
$('#ifm1').load(function(){
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
console.log(obj)
//上传后增加预览模式
$('#preview').empty(); //清空原有相同文件
var imgTag = document.createElement('img'); //创建img标签
imgTag.src = "/" + obj.data; //路径
$('#preview').append(imgTag);
})
}
</script>
</body>
</html>
#HTML文件
3.2选择图片后预览
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>upload_iframe</title>
<style>
/* 设置显示上传后图片的样式*/
.img{
250px;
height: 250px;
}
</style>
</head>
<body>
<iframe id="my_iframe" name="my_iframe" style="display: none" src=""></iframe>
<form id="fo" method="POST" action="/upload_iframe.html/" enctype="multipart/form-data" target="my_iframe">
{# <input type="text" id="user" name="user"/>#}
<input type="file" id="img" name="img" onchange="UploadFile3();"/>
{# <input type="submit"/>#}
</form>
<div id="container"></div>
<script src="/static/js/jquery-3.5.1.js"></script>
<script>
function UploadFile3() {
// onload事件会在页面或者图像加载完成后立即触发
document.getElementById('my_iframe').onload = callback;
// target 属性指定在何处打开表单中的 action-URL
{#document.getElementById('fo').target = 'my_iframe'#}
// 提交
document.getElementById('fo').submit();
}
function callback() {
// 使用contents(),可以将iframe中内嵌的页面HTML内容取出,取出的数据为字符串格式
var text = $('#my_iframe').contents().find('body').text();
// 字符串通过json转化为字典
var json_data = JSON.parse(text);
console.log(json_data);
if (json_data.status) {
// 创建一个img的元素
var tag = document.createElement('img');
// 字符串拼接
tag.src = '/' + json_data.data;
tag.className = 'img';
tag.classList.add("image")
// 添加到目标元素标签内
$('#container').empty().append(tag);
} else {
alert(json_data.error)
}
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="form1" method="post" action="/upload_file/" enctype="multipart/form-data" target="ifm1">
<iframe id="iframe" name="ifm1" style="display: none"></iframe>
<input type="file" name="send" onchange="changeupload();"/>
{# <input type="submit" onclick="iframesubmit()" value="Form表单提交"/>#}
</form>
<div id="preview"></div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
function changeupload() {
$("#iframe").load(function () {
var text = $('#iframe').contents().find('body').text();
var obj = JSON.parse(text);
console.log(obj)
//上传后增加预览模式
$('#preview').empty();//清空原有相同文件
var imgTag = document.createElement('img');//创建img标签
imgTag.src = "/" + obj.data;//路径
$('#preview').append(imgTag);
})
$('#form1').submit();
}
</script>
</body>
</html>
#HTML文件
