框架----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),
]
View Code

3. views

 1 from django.shortcuts import render,HttpResponse,redirect
 2 
 3 def index(request):
 4     return render(request,'index.html')
 5 
 6 
 7 def add1(request):
 8     a1 = int(request.POST.get('i1'))
 9     a2 = int(request.POST.get('i2'))
10     return HttpResponse(a1 + a2)
11 
12 def add2(request):
13     if request.method == 'GET':
14         i1 = int(request.GET.get('i1'))
15         i2 = int(request.GET.get('i2'))
16         print('add2....')
17         return HttpResponse(i1 + i2)
18     else:
19         print(request.POST)
20         print(request.body)
21         return HttpResponse('...')
22 
23 
24 def autohome(request):
25     return render(request,'autohome.html')
26 
27 
28 def fake_ajax(request):
29     if request.method == 'GET':
30         return render(request,'fake_ajax.html')
31     else:
32         print(request.POST)
33         return HttpResponse('返回值')
34 
35 
36 def jsonp(request):
37     return render(request,'jsonp.html')
views

4. templates

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <h1>首页</h1>
 9     <input type="text" id="i1" />
10     +
11     <input type="text" id="i2" />
12     =
13     <input type="text" id="i3" />
14 
15     <input type="button" id="btn1" value="jQuery Ajax" onclick="add1();" />
16     <input type="button" id="btn2" value="原生Ajax" onclick="add2();" />
17 
18     <script src="/static/jquery-3.2.1.js"></script>
19     <script>
20     /* $$$$$$$ jQuery Ajax $$$$$$$ */
21         function add1() {
22             $.ajax({
23                 url:'/add1/',
24                 type:'POST',
25                 data:{'i1':$('#i1').val(),'i2':$('#i2').val()},
26                 success:function (arg) {
27                     $('#i3').val(arg);
28                 }
29             })
30 
31         }
32 
33 
34      /* $$$$$$$ 原生Ajax $$$$$$$ */
35         function add2() {
36     /* $$$$$$$  GET方式  $$$$$$$ */
37         /*    var xhr = new XMLHttpRequest();
38             xhr.onreadystatechange = function () {
39                 if(xhr.readyState == 4){
40                     alert(xhr.responseText);
41                 }
42             };
43             xhr.open('GET','/add2/?i1=12&i2=19');
44             xhr.send();  */
45 
46 
47 
48     /* $$$$$$$  POST方式  $$$$$$$ */
49             var xhr = new XMLHttpRequest();
50             xhr.onreadystatechange = function () {
51                 if(xhr.readyState == 4){
52                     alert(xhr.responseText);
53                 }
54             };
55             xhr.open('POST','/add2/');
56             xhr.setRequestHeader('Content-Typr','application/x-www-form-urlencoded');
57             xhr.send('i1=12&i2=19');
58         }
59     </script>
60 </body>
61 </html>
index.html
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <div>
 9         <input type="text" id="txt1" />
10         <input type="button" value="查看" onclick="changeScr();" />
11     </div>
12     <iframe id="ifr" style=" 1200px;height: 1000px;" src="http://www.autohome.com.cn"></iframe>
13 
14     <script>
15         function changeScr() {
16             var inp = document.getElementById('txt1').value;
17             document.getElementById('ifr').src = inp;
18         }
19     </script>
20 </body>
21 </html>
autohome.html
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6 </head>
 7 <body>
 8     <form id="f1" method="POST" action="/fake_ajax/" target="ifr">
 9         <iframe id="ifr" name="ifr" style="display: none;"></iframe>
10         <input type="text" name="user" />
11         <a onclick="submitForm();">提交</a>
12     </form>
13 
14     <script>
15         function submitForm() {
16             document.getElementById('ifr').onload = loadIframe;
17             document.getElementById('f1').submit();
18         }
19         function loadIframe() {
20             var content = document.getElementById('ifr').contentWindow.document.body.innerText;
21             alert(content);
22         }
23     </script>
24 </body>
25 </html>
fake_ajax.html
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <script src="/static/commons.js"></script>
 7 </head>
 8 <body>
 9     <a onclick="sendMsg();">发送</a>
10     <script>
11         function sendMsg() {
12             var tag = document.createElement('scaript');
13             tag.src = "http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403";
14             document.head.appendChild(tag);
15         }
16     </script>
17 </body>
18 </html>
jsonp.html

5. static

1 function list(arg){
2     console.log(arg);
3 }
commons
1 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
1 from django.shortcuts import render,HttpResponse
2 
3 # Create your views here.
4 
5 
6 def cors(request):
7     return render(request,"core.html")
8 
9 view.py
view.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 
 9 <input type="button" value="获取用户列表" onclick="getUsers()">
10 
11 <ul id="user_list"></ul>
12 
13 <script src="/static/jquery-3.2.1.js"></script>
14 
15 <script>
16     function getUsers() {
17         $.ajax({
18             url:"http://www.s5.com:9000/user/",
19             type:"GET",
20             success:function (arg) {
21                 console.log(arg);
22                 console.log(typeof arg);
23                 for (var i = 0; i < arg.length; i++) {
24                  var tag = document.createElement("li");
25                 tag.innerText = arg[i];
26                 document.getElementById("user_list").appendChild(tag);
27                 }
28             }
29         })
30     }
31 </script>
32 
33 
34 
35 </body>
36 </html>
37 
38 core.html
core.html

2. www.s5.com

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

    url(r'^user', views.user),
]
urls.py
 1 from django.shortcuts import render,HttpResponse
 2 
 3 # Create your views here.
 4 
 5 import json
 6 def user(request):
 7 
 8     user_list = ["alex","egon","root"]
 9     user_list_str = json.dumps(user_list)
10 
11     obj = HttpResponse(user_list_str)
12 
13     obj["Access-Control-Allow-Origin"] = "http://www.s4.com:8000"
14     return obj
15 
16 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
 1 from django.shortcuts import render,HttpResponse
 2 
 3 # Create your views here.
 4 
 5 
 6 
 7 def cors(request):
 8     return render(request,"core.html")
 9 
10 views.py
views.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 
 9 <input type="button" value="获取用户列表" onclick="getUsers()">
10 
11 <ul id="user_list"></ul>
12 
13 <script src="/static/jquery-3.2.1.js"></script>
14 
15 <script>
16     function getUsers() {
17         $.ajax({
18             url:"http://www.s5.com:9000/user/",
19             type:"DELETE",
20             success:function (arg) {
21                 console.log(arg);
22                 
23             }
24         })
25     }
26 </script>
27 
28 
29 
30 </body>
31 </html>
32 
33 core.html
core.html

2. www.s5.com

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

    url(r'^user', views.user),
]
urls
 1 from django.shortcuts import render,HttpResponse
 2 
 3 # Create your views here.
 4 
 5 import json
 6 def user(request):
 7     print(request.method)
 8     if request.method == "OPTIONS":
 9 
10         obj = HttpResponse()
11         obj["Access-Control-Allow-Origin"] = "*"
12         obj["Access-Control-Allow-Methods"] = "DELETE"
13         return obj
14 
15     obj = HttpResponse("..")
16     obj["Access-Control-Allow-Origin"] = "*"
17     return obj
18 
19 view.py
views.py
原文地址:https://www.cnblogs.com/wangyongsong/p/7127608.html