框架----Django之Ajax全套实例(原生AJAX,jQuery Ajax,“伪”AJAX,JSONP,CORS)

一、原生AJAX,jQuery Ajax,“伪”AJAX,JSONP

1. 浏览器访问

http://127.0.0.1:8000/index/

http://127.0.0.1:8000/fake_ajax/

http://127.0.0.1:8000/index/jsonp/

http://127.0.0.1:8000/autohome/

2. urls

from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^add1/', views.add1),
url(r'^add2/', views.add2),
url(r'^autohome/', views.autohome),
url(r'^fake_ajax/', views.fake_ajax),
url(r'^jsonp/', views.jsonp),
]

3. views

 from django.shortcuts import render,HttpResponse,redirect

 def index(request):
return render(request,'index.html') def add1(request):
a1 = int(request.POST.get('i1'))
a2 = int(request.POST.get('i2'))
return HttpResponse(a1 + a2) def add2(request):
if request.method == 'GET':
i1 = int(request.GET.get('i1'))
i2 = int(request.GET.get('i2'))
print('add2....')
return HttpResponse(i1 + i2)
else:
print(request.POST)
print(request.body)
return HttpResponse('...') def autohome(request):
return render(request,'autohome.html') def fake_ajax(request):
if request.method == 'GET':
return render(request,'fake_ajax.html')
else:
print(request.POST)
return HttpResponse('返回值') def jsonp(request):
return render(request,'jsonp.html')

views

4. templates

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>首页</h1>
<input type="text" id="i1" />
+
<input type="text" id="i2" />
=
<input type="text" id="i3" /> <input type="button" id="btn1" value="jQuery Ajax" onclick="add1();" />
<input type="button" id="btn2" value="原生Ajax" onclick="add2();" /> <script src="/static/jquery-3.2.1.js"></script>
<script>
/* $$$$$$$ jQuery Ajax $$$$$$$ */
function add1() {
$.ajax({
url:'/add1/',
type:'POST',
data:{'i1':$('#i1').val(),'i2':$('#i2').val()},
success:function (arg) {
$('#i3').val(arg);
}
}) } /* $$$$$$$ 原生Ajax $$$$$$$ */
function add2() {
/* $$$$$$$ GET方式 $$$$$$$ */
/* var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
alert(xhr.responseText);
}
};
xhr.open('GET','/add2/?i1=12&i2=19');
xhr.send(); */ /* $$$$$$$ POST方式 $$$$$$$ */
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
alert(xhr.responseText);
}
};
xhr.open('POST','/add2/');
xhr.setRequestHeader('Content-Typr','application/x-www-form-urlencoded');
xhr.send('i1=12&i2=19');
}
</script>
</body>
</html>

index.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<input type="text" id="txt1" />
<input type="button" value="查看" onclick="changeScr();" />
</div>
<iframe id="ifr" style="width: 1200px;height: 1000px;" src="http://www.autohome.com.cn"></iframe> <script>
function changeScr() {
var inp = document.getElementById('txt1').value;
document.getElementById('ifr').src = inp;
}
</script>
</body>
</html>

autohome.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="f1" method="POST" action="/fake_ajax/" target="ifr">
<iframe id="ifr" name="ifr" style="display: none;"></iframe>
<input type="text" name="user" />
<a onclick="submitForm();">提交</a>
</form> <script>
function submitForm() {
document.getElementById('ifr').onload = loadIframe;
document.getElementById('f1').submit();
}
function loadIframe() {
var content = document.getElementById('ifr').contentWindow.document.body.innerText;
alert(content);
}
</script>
</body>
</html>

fake_ajax.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="/static/commons.js"></script>
</head>
<body>
<a onclick="sendMsg();">发送</a>
<script>
function sendMsg() {
var tag = document.createElement('scaript');
tag.src = "http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403";
document.head.appendChild(tag);
}
</script>
</body>
</html>

jsonp.html

5. static

 function list(arg){
console.log(arg);
}

commons

 f1(123)

commons2

二、CORS

cors 跨站资源共享

#响应头加入
obj["Access-Control-Allow-Origin"] = "http://www.s4.com:8000" #仅这个域名可以访问
obj["Access-Control-Allow-Origin"] = "*" #所有域名都可以访问

a. www.s4.com 访问 www.s5.com,在响应头加入数据,同源策略就不生效 

1. www.s4.com

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^cors/', views.cors),
]

urls.py

 from django.shortcuts import render,HttpResponse

 # Create your views here.

 def cors(request):
return render(request,"core.html") view.py

view.py

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <input type="button" value="获取用户列表" onclick="getUsers()"> <ul id="user_list"></ul> <script src="/static/jquery-3.2.1.js"></script> <script>
function getUsers() {
$.ajax({
url:"http://www.s5.com:9000/user/",
type:"GET",
success:function (arg) {
console.log(arg);
console.log(typeof arg);
for (var i = 0; i < arg.length; i++) {
var tag = document.createElement("li");
tag.innerText = arg[i];
document.getElementById("user_list").appendChild(tag);
}
}
})
}
</script> </body>
</html> core.html

core.html

2. www.s5.com

urlpatterns = [
url(r'^admin/', admin.site.urls), url(r'^user', views.user),
]

urls.py

 from django.shortcuts import render,HttpResponse

 # Create your views here.

 import json
def user(request): user_list = ["alex","egon","root"]
user_list_str = json.dumps(user_list) obj = HttpResponse(user_list_str) obj["Access-Control-Allow-Origin"] = "http://www.s4.com:8000"
return obj views.py

views.py

b.预检request.method == "OPTIONS

1. www.s4.com

urlpatterns = [
url(r'^admin/', admin.site.urls), url(r'^cors/', views.cors),
]

urls.py

 from django.shortcuts import render,HttpResponse

 # Create your views here.

 def cors(request):
return render(request,"core.html") views.py

views.py

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <input type="button" value="获取用户列表" onclick="getUsers()"> <ul id="user_list"></ul> <script src="/static/jquery-3.2.1.js"></script> <script>
function getUsers() {
$.ajax({
url:"http://www.s5.com:9000/user/",
type:"DELETE",
success:function (arg) {
console.log(arg); }
})
}
</script> </body>
</html> core.html

core.html

2. www.s5.com

urlpatterns = [
url(r'^admin/', admin.site.urls), url(r'^user', views.user),
]

urls

 from django.shortcuts import render,HttpResponse

 # Create your views here.

 import json
def user(request):
print(request.method)
if request.method == "OPTIONS": obj = HttpResponse()
obj["Access-Control-Allow-Origin"] = "*"
obj["Access-Control-Allow-Methods"] = "DELETE"
return obj obj = HttpResponse("..")
obj["Access-Control-Allow-Origin"] = "*"
return obj view.py

views.py

上一篇:原生JS写的ajax函数


下一篇:【背景建模】SACON