一.Ajax向本地后台发送数据:
方式一:引入JQuery通过Ajax发送GET请求
(1)URL:xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index.html$', views.index), url(r'^ajax1.html$', views.ajax1), #提交的数据 ]
(2)视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def index(request): #主页面发送请求 return render(request,'index.html') def ajax1(request): #接收ajax提交的数据 print(request.GET) #接收到:<QueryDict: {'xixi': ['123']}> return HttpResponse('...')
(3)发送页面:xixi\templates\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> {#点击按钮CSS#} .btn{ display: inline-block; padding: 5px 10px; background-color: coral; color: white; } </style> </head> <body> <h1>引入JQuery通过Ajax发送GET请求</h1> <div> <a class="btn" onclick="AjaxSubmit1();">点击</a> </div> <script src="/static/js/jquery-3.1.1.js"></script> <script> function AjaxSubmit1() { {#Query_Ajax发送GET请求#} $.ajax({ url: '/ajax1.html', {#传给ajax1.html#} type:'GET', {#GET方式#} data: {'xixi':123}, {#传输数据#} success:function (arg) { } }) } </script> </body> </html>
访问点击:http://127.0.0.1:8080/index.html

服务端接收到:
[21/Mar/2019 11:38:57] "GET /ajax1.html?xixi=123 HTTP/1.1" 200 3
<QueryDict: {'xixi': ['123']}>
方式二:引入JQuery通过Ajax发送POST请求
(1)URL:xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index.html$', views.index), url(r'^ajax1.html$', views.ajax1), #提交的数据 ]
(2)视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def index(request): #主页面发送请求 return render(request,'index.html') def ajax1(request): #接收ajax提交的数据 print(request.POST) #接收到:<QueryDict: {'xixi': ['123']}> return HttpResponse('...')
(3)发送页面:xixi\templates\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> {#点击按钮CSS#} .btn{ display: inline-block; padding: 5px 10px; background-color: coral; color: white; } </style> </head> <body> <h1>引入JQuery通过Ajax发送POST请求</h1> <div> <a class="btn" onclick="AjaxSubmit2();">点击</a> </div> <script src="/static/js/jquery-3.1.1.js"></script> <script> function AjaxSubmit2() { {#Query_Ajax发送GET请求#} $.ajax({ url: '/ajax1.html', {#传给ajax1.html#} type:'POST', {#POST方式#} data: {'xixi':123}, {#传输数据#} success:function (arg) { } }) } </script> </body> </html>
访问点击:http://127.0.0.1:8080/index.html

服务端接收到:
<QueryDict: {'xixi': ['123']}>
[21/Mar/2019 12:06:41] "POST /ajax1.html HTTP/1.1" 200 3
方式三:通过原生Ajax叫XMLHttpRequest对象发送GET请求
(1)URL:xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index.html$', views.index), url(r'^ajax1.html$', views.ajax1), #提交的数据 ]
(2)视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def index(request): #主页面发送请求 return render(request,'index.html') def ajax1(request): #接收ajax提交的数据 print(request.GET) #接收到:<QueryDict: {'xixi': ['123']}> return HttpResponse('...')
(3)发送页面:xixi\templates\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> {#点击按钮CSS#} .btn{ display: inline-block; padding: 5px 10px; background-color: coral; color: white; } </style> </head> <body> <h1>通过原生Ajax叫XMLHttpRequest对象发送GET请求</h1> <div> <a class="btn" onclick="AjaxSubmit1();">点击</a> </div> <script> function AjaxSubmit1() { var xhr = new XMLHttpRequest(); {#创建XMLHttpRequest对象赋值给xhr#} xhr.onreadystatechange = function () { {#在send前设置回调,onreadystatechange回调函数当某个状态更改的时候执行#} if(xhr.readyState == 4){ {#状态等于4是接收完毕服务器返回的数据#} console.log(xhr.responseText); {#接收的数据在responseText#} } }; xhr.open('GET','/ajax1.html?xixi=123'); {#利用open方法以GET方式向ajax1.html创建连接#} xhr.send(null); {#send发送连接,GET方式为null#} } </script> </body> </html>
访问点击:http://127.0.0.1:8080/index.html

服务端接收到:
<QueryDict: {'xixi': ['123']}>
[21/Mar/2019 11:50:35] "GET /ajax1.html?xixi=123 HTTP/1.1" 200 3
方式四:通过原生Ajax叫XMLHttpRequest对象发送POST请求
(1)URL:xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index.html$', views.index), url(r'^ajax1.html$', views.ajax1), #提交的数据 ]
(2)视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def index(request): #主页面发送请求 return render(request,'index.html') def ajax1(request): #接收ajax提交的数据 print(request.GET) #接收到:<QueryDict: {'xixi': ['123']}> return HttpResponse('...')
(3)发送页面:xixi\templates\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> {#点击按钮CSS#} .btn{ display: inline-block; padding: 5px 10px; background-color: coral; color: white; } </style> </head> <body> <h1>通过原生Ajax叫XMLHttpRequest对象发送POST请求</h1> <div> <a class="btn" onclick="AjaxSubmit2();">点击</a> </div> <script> function AjaxSubmit2() { var xhr = new XMLHttpRequest(); {#创建XMLHttpRequest对象赋值给xhr#} xhr.onreadystatechange = function () { {#在send前设置回调,onreadystatechange回调函数当某个状态更改的时候执行#} if(xhr.readyState == 4){ {#状态等于4是接收完毕服务器返回的数据#} console.log(xhr.responseText); {#接收的数据在responseText#} } }; xhr.open('POST','/ajax1.html'); {#利用open方法以POST方式向ajax1.html创建连接#} xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); {#POST需要把请求头也发到服务端,才能把发过去的数据从body里转换到POST里#} xhr.send("xixi=123"); {#send发送连接和内容#} } </script> </body> </html>
访问点击:http://127.0.0.1:8080/index.html

服务端接收到:
<QueryDict: {'xixi': ['123']}>
[21/Mar/2019 12:11:34] "POST /ajax1.html HTTP/1.1" 200 3
方式五:伪造Ajax请求通过iframe标签+form表单
(1)URL:xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index.html$', views.index), url(r'^ajax1.html$', views.ajax1), #提交的数据 ]
(2)视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def index(request): #主页面发送请求 return render(request,'index.html') def ajax1(request): #接收ajax提交的数据 print(request.POST) #接收到:<QueryDict: {'xixi': ['123']}> ret = {'status': True, 'message': '....'} import json return HttpResponse(json.dumps(ret))
(3)发送页面:xixi\templates\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> {#点击按钮CSS#} .btn{ display: inline-block; padding: 5px 10px; background-color: coral; color: white; } </style> </head> <body> <h1>基于Iframe+Form表单实现伪造ajax</h1> <div> <iframe id="iframe" name="ifra"></iframe> {#设定iframe(不刷新的特性,提交后返回的值在iframe里) #} <form id="fm" action="/ajax1.html" method="POST" target="ifra"> {#设定from(提交数据),from和ifram关联,target="ifra" #} <input name="xixi" value="123" /> <a onclick="AjaxSubmit1()">提交</a> {#通过a标签把表单提交,把a标签绑定事件#} </form> </div> <script src="/static/js/jquery-3.1.1.js"></script> <script> function AjaxSubmit1() { document.getElementById('iframe').onload = reloadIframe; //在提交过去之前给iframe绑定onload事件 document.getElementById('fm').submit(); //找到fm表单提交 } function reloadIframe() { //当数据返回回来自动执行调用reloadIframe var content = this.contentWindow.document.body.innerHTML; //this=当前标签,回调函数的内容 var obj = JSON.parse(content); //把content转换成对象 if(obj.status){ alert(obj.message); //弹出框 } } </script> </body> </html>
访问点击:http://127.0.0.1:8080/index.html

服务端接收到:
<QueryDict: {'xixi': ['123']}>
[21/Mar/2019 14:46:38] "POST /ajax1.html HTTP/1.1" 200 35
二.Ajax向后台发送文件:
1.通过FormData文件上传
(1)URL:xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index.html$', views.index), url(r'^ajax1.html$', views.ajax1), #提交的数据 ]
(2)视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def index(request): #主页面发送请求 return render(request,'index.html') def ajax1(request): #接收ajax提交的数据 print(request.POST) print(request.FILES) ret = {'status': True, 'message': '....'} import json return HttpResponse(json.dumps(ret))
(3)发送页面:xixi\templates\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> {#点击按钮CSS#} .btn{ display: inline-block; padding: 5px 10px; background-color: coral; color: white; } </style> </head> <body> <h1>通过FormData文件上传</h1> <input type="file" id="img" /> <a class="btn" onclick="AjaxSubmit1();">上传</a> <script src="/static/js/jquery-3.1.1.js"></script> <script> function AjaxSubmit1() { document.getElementById('img')[0] //获取到上传文件img选择器对象,[0]代表上传的文件对象 var data = new FormData(); //创建FormData对象封装文件信息和文件内容到data data.append('k1','v1'); //上传的文本,构造特殊的字典 data.append('k3',document.getElementById('img').files[0]); //上传的文件对象 $.ajax({ url: '/ajax1.html', type: 'POST', data:data, //data获取文件 success:function (arg) { //传给后端 console.log(arg) //在控制台上输出 }, processData: false, //tell jQuery not to process the data contentType: false //tell jQuery not to set contentType }) } </script> </body> </html>
访问发送文件:http://127.0.0.1:8080/index.html
服务端接收到:
<QueryDict: {'k1': ['v1']}>
<MultiValueDict: {'k3': [<InMemoryUploadedFile: 笔记.txt (text/plain)>]}>
[21/Mar/2019 15:58:06] "POST /ajax1.html HTTP/1.1" 200 35
2.基于Iframe+Form表单实现伪造ajax文件上传
(1)URL:xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index.html$', views.index), url(r'^ajax1.html$', views.ajax1), #提交的数据 ]
(2)视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def index(request): #主页面发送请求 return render(request,'index.html') def ajax1(request): #接收ajax提交的数据 print(request.POST) print(request.FILES) ret = {'status': True, 'message': '....'} import json return HttpResponse(json.dumps(ret))
(3)发送页面:xixi\templates\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> {#点击按钮CSS#} .btn{ display: inline-block; padding: 5px 10px; background-color: coral; color: white; } </style> </head> <body> <h1>基于Iframe+Form表单实现伪造ajax文件上传</h1> <iframe style="display: none" id="iframe1" name="ifra1"></iframe> {#设定iframe(不刷新的特性,提交后返回的值在iframe里) #} <form id="fm1" action="/ajax1.html" method="POST" enctype="multipart/form-data" target="ifra1"> {#文件上传enctype="multipart/form-data" #} <input type="text" name="k1" /> <input type="text" name="k2" /> <input type="file" name="k3" /> <a class="btn" onclick="AjaxSubmit1()">上传</a> {#通过a标签把表单提交,把a标签绑定事件#} </form> <script src="/static/js/jquery-3.1.1.js"></script> <script> function AjaxSubmit1() { document.getElementById('iframe1').onload = reloadIframe; //在提交过去之前给iframe绑定onload事件 document.getElementById('fm1').submit(); //找到fm表单提交 } function reloadIframe() { var content = this.contentWindow.document.body.innerHTML; //this=当前标签,回调函数的内容 var obj = JSON.parse(content); //把content转换成对象 console.log(obj); //在控制台上输出 } </script> </body> </html>
访问上传:http://127.0.0.1:8080/index.html
服务端接收到:
<QueryDict: {'k1': ['xixi'], 'k2': ['123']}>
<MultiValueDict: {'k3': [<InMemoryUploadedFile: 笔记.txt (text/plain)>]}>
[21/Mar/2019 16:30:56] "POST /ajax1.html HTTP/1.1" 200 35
3.Ajax往本地上传图片后并显示图片
(1)URL:xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^upload.html$', views.upload), url(r'^upload_img.html$', views.upload_img), ]
(2)视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse import json def upload(request): #主页函数 return render(request,'upload.html') def upload_img(request): #接收上传文件函数 import os import uuid nid = str(uuid.uuid4()) #生成随机字符串 ret = {'status':True,'data':None,'message':None} #定义ret给用户返回用 obj = request.FILES.get('k3') #k3对象(文件大小,文件名称,文件内容等)因为发送name=k3,所以接收的名字也是k3赋值给obj file_path = os.path.join('static', nid+obj.name) #file_path上传文件存放的绝对路径(static/随机字符串+文件名) f = open(file_path,'wb') #在服务器端创建一个文件(文件名跟用户提交的文件名一样) for line in obj.chunks(): #去obj里一块一块的拿内容 f.write(line) #每拿一点写一点 f.close() ret['data'] = file_path #把路径存放在data里会随ret返回给用户 return HttpResponse(json.dumps(ret)) #把ret给用户返回
(3)上传显示页面:xixi\templates\index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .btn{ display: inline-block; padding: 5px 10px; color: white; } </style> </head> <body> <iframe style="display: none" id="iframe1" name="ifra1"></iframe> <form id="fm1" action="/upload_img.html" method="POST" enctype="multipart/form-data" target="ifra1"> <input type="file" name="k3" onchange="uploadFile();" /> {#点击预览文件的时候触发#} </form> <h3>预览上传照片</h3> <div id="preview"> {#如果上传成功让preview里新增img标签#} </div> <script src="/static/js/jquery-3.1.1.js"></script> <script> function uploadFile() { document.getElementById('iframe1').onload = reloadIframe1; //在提交过去之前给iframe绑定onload事件当数据返回回来自动执行调用reloadIframe1 document.getElementById('fm1').submit(); //找到fm1标签做提交把要上传的文件传到后台 } function reloadIframe1() { var content = this.contentWindow.document.body.innerHTML; //this=当前标签,里面是回调函数的内容赋值给content var obj = JSON.parse(content); //把content转换成对象 var tag = document.createElement('img'); //生成img标签 tag.src = obj.data; //等于后端传过来的上传照片的路径 $('#preview').empty().append(tag); //给preview添加照片显示(每次添加前empty()清空历史) } </script> </body> </html>
访问上传图片后:http://127.0.0.1:8080/upload.html
三、通过JSONP方式进行跨域Ajax
1.浏览器同源策略:XMLHttpRequest遵循这个策略只能往本地发请求,巧妙的机制JSONP可以往别的网站发
2.JSONP:执行方式:
(1)本地利用创建script块,在其中执行src属性为远程的url
(2)在服务端返回的时候把数据包裹一个函数:函数(返回值)
(3)本地定义一个函数执行:
function 函数(arg){
}
3.手动实现JSONP方式:
(1)远程服务器:URL:\xi\xi\urls.py
from django.conf.urls import url from django.contrib import admin from yao import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^yao.html$', views.yao), ]
(2)远程服务器视图函数:xi\yao\views.py
from django.shortcuts import render,HttpResponse def yao(request): return HttpResponse('func("我是远程服务器");') #遵循JSONP格式函数(返回值)
访问:http://127.0.0.1:8000/yao.html
返回:func("我是远程服务器");
(1)本地服务器URL:\xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^jsonp.html$', views.jsonp), #发送主页 ]
(2)本地服务器视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def jsonp(request): return render(request,'jsonp.html')
(3)本地服务器页面:xixi\templates\jsonp.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="content"></div> <input type="button" value="JSONP方式" onclick="submitJsonp1();" /> <script src="/static/js/jquery-3.1.1.js"></script> <script> function submitJsonp1() { var tag = document.createElement('script'); //第一:创建script标签[利用script不受同源策略机制] tag.src = 'http://127.0.0.1:8000/yao.html'; //把src路径写上远程地址路径(src相当于是js文件,返回的内容是"func("我是远程服务器")") document.head.appendChild(tag); //发一个请求在head里加上这个script标签 document.head.removeChild(tag); //然后删掉 } function func(arg) { //第二:返回的数据是以js代码进行解释的给它包裹一个函数func,在本地执行远端传来的func函数---func("我是远程服务器") $('#content').html(arg); //拿到数据返回到页面 } </script> </body> </html>
访问点击JSONP方式:http://127.0.0.1:8080/jsonp.html
返回结果: 
4.通过jquery类库实现JSONP:
远程服务器:
(1)远程服务器URL:\xi\xi\urls.py
from django.conf.urls import url from django.contrib import admin from yao import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^yao.html$', views.yao), ]
(2)远程服务器视图函数:xi\yao\views.py
from django.shortcuts import render,HttpResponse def yao(request): name = request.GET.get('callback') #传的函数名 return HttpResponse('%s("我是远程服务器");' %(name)) #遵循JSONP格式函数(返回值)
访问:http://127.0.0.1:8000/yao.html
返回:func("我是远程服务器");
(1)本地服务器URL:\xixi\xixi\urls.py
from django.conf.urls import url from django.contrib import admin from ajax_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^jsonp.html$', views.jsonp), #发送主页 ]
(2)本地服务器视图函数:xixi\ajax_app\views.py
from django.shortcuts import render,HttpResponse def jsonp(request): return render(request,'jsonp.html')
(3)本地服务器页面:xixi\templates\jsonp.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="content"></div> <input type="button" value="JSONP方式" onclick="submitJsonp1();" /> <script src="/static/js/jquery-3.1.1.js"></script> <script> function submitJsonp1() { $.ajax({ //$.ajax方式发(内部创建script标签) url: 'http://127.0.0.1:8000/yao.html', //远程地址路径, type: 'GET', //jsonp只能发GET请求 dataType: 'jsonp', //加上jsonp后就不会通过XMLHttpRequest对象发送,在内部创建script代码在head里增加后在删除掉 jsonp: 'callback', //callbak表示?callback= jsonpCallback: 'func' //func表示?callback等于号后面的func }) } function func(arg) { //执行func函数 $('#content').html(arg); //拿到数据返回到页面 } </script> </body> </html>
访问点击JSONP:http://127.0.0.1:8080/jsonp.html
返回:
se(content);
浙公网安备 33010602011771号