AJAX大全

1.
Python序列化
字符串 = json.dumps(对象) 对象->字符串
对象 = json.loads(字符串) 字符串->对象

JavaScript:
字符串 = JSON.stringify(对象) 对象->字符串
对象 = JSON.parse(字符串) 字符串->对象

应用场景:
数据传输时,
发送:字符串
接收:字符串 -> 对象
2. ajax

$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':'v1'},
success:function(arg){
// arg是字符串类型
// var obj = JSON.parse(arg)
}
})


$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':'v1'},
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})


$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':[1,2,3,4]},
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})

发送数据时:
data中的v

a. 只是字符串或数字
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':'v1'},
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})
b. 包含属组
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':[1,2,3,4]},
dataType: 'JSON',
traditional: true,
success:function(arg){
// arg是对象
}
})

c. 传字典

b. 包含属组
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1': JSON.stringify({}) },
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})



3. 事件委托

$('要绑定标签的上级标签').on('click','要绑定的标签',function(){})

$('要绑定标签的上级标签').delegate('要绑定的标签','click',function(){})

 

AJAX与原生JS

 1 <a class="abtn"  onclick="jQueryAjax1()">jQuery_ajax</a>
 2 <a class="abtn"  onclick="jsAjax2()">js_ajax</a>
 3 
 4  <script src="/static/js/jquery-3.1.1.js"></script>
 5     <script>
 6 
 7         function jQueryAjax1() {
 8             $.ajax({
 9                 url:'{% url "Ajax1" %}',
10                 type:'GET',
11                 data:{"number":123},
12                 success:function (arg) {
13                     console.log(arg)
14                 }
15             })
16         }
17 
18         function jsAjax2() {
19             var xhr = new XMLHttpRequest();
20             xhr.onreadystatechange=function () {
21                 if (xhr.readyState==4 ){
22                     //服务端返回数据接受完毕
23                     console.log(xhr.responseText)
24                 }
25             };
26 
27             xhr.open('GET','{% url "Ajax1" %}?number2=123');
28             xhr.send(null);
29 
30         }
31 
32     </script>
GET方式
        <a class="abtn"  onclick="jQueryAjax1()">jQuery_ajax</a>
        <a class="abtn"  onclick="jsAjax2()">js_ajax</a>    

    <script src="/static/js/jquery-3.1.1.js"></script>
    <script>

        function jQueryAjax1() {
            $.ajax({
                url:'{% url "Ajax1" %}',
                type:'POST',
                data:{"number":123},
                success:function (arg) {
                    console.log(arg)
                }
            })
        }

        function jsAjax2() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange=function () {
                if (xhr.readyState==4 ){
                    //服务端返回数据接受完毕
                    console.log(xhr.responseText)
                }
            };

            xhr.open('POST','{% url "Ajax1" %}');
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            var content = "appid=11111&sign=222222222";
            xhr.send(content);

        }

    </script>
POST方式

 伪AJAX:iframe+form

 1     <h4>方式三:AJAX "伪造"</h4>
 2     <div>
 3         <h6>基于Iframe+Form表单</h6>
 4         <iframe name="frame"></iframe>
 5         <form id="fm" action="{% url 'Ajax1'%}" method="post" target="frame">
 6             <input name="username" value="root">
 7             <a class="abtn" onclick="Ajaxsubmit()">伪造AJAX提交</a>
 8         </form>
 9     </div>
10 
11     <script src="/static/js/jquery-3.1.1.js"></script>
12     <script>
13 
14         function Ajaxsubmit() {
15             document.getElementById("fm").submit();
16         }
17 
18 
19     </script>
伪AJAX(一)
 1 <h4>方式三:AJAX "伪造"</h4>
 2     <div>
 3         <h6>基于Iframe+Form表单</h6>
 4         <iframe id="iframe" name="frame" ></iframe>
 5         <form id="fm" action="{% url 'Ajax1'%}" method="post" target="frame">
 6             <input name="username" value="root">
 7             <a class="abtn" onclick="Ajaxsubmit()">伪造AJAX提交</a>
 8         </form>
 9     </div>
10 
11     <script src="/static/js/jquery-3.1.1.js"></script>
12     <script>
13         
14         function Ajaxsubmit() {
15             document.getElementById('iframe').onload=reload;
16             document.getElementById("fm").submit();
17         }
18         
19         function reload() {
20             //js获取iframe内body返回值
21             console.log(this.contentWindow.document.body.innerHTML);
22             //jquery获取iframe内body返回值
23             console.log($(this).contents().find('body').html());
24             //.................................................................
25             var content = this.contentWindow.document.body.innerHTML;
26             var obj= JSON.parse(content);
27             if (obj.status==200){
28                 alert(obj.message);
29             }
30         }
31 
32 
33     </script>
AJAX "伪造"

 AJAX上传图片

 1     <h4>方式一:Jquery 文件上传</h4>
 2     <div>
 3         <input type="file" id="img">
 4         <a class="abtn" onclick="file1()">Jquery 上传</a>
 5     </div>
 6 
 7     <script src="/static/js/jquery-3.1.1.js"></script>
 8     <script>
 9         
10         function file1() {
11             var data=new FormData();
12             data.append("file_key",document.getElementById('img').files[0]);
13             $.ajax({
14                 url:'{% url "Ajax2" %}',
15                 type:'POST',
16                 data:data,
17                 processData: false,  // tell jQuery not to process the data
18                 contentType: false,  // tell jQuery not to set contentType
19                 success:function (arg) {
20                     console.log(arg)
21                 }
22             })
23         }
24 
25 
26     </script>
Jquery方式(一)
 1     <h4>方式二:JS 文件上传</h4>
 2     <div>
 3         <input type="file" id="img">
 4         <a class="abtn" onclick="file2()">Js 上传</a>
 5     </div>
 6 
 7  <script src="/static/js/jquery-3.1.1.js"></script>
 8     <script>
 9 
10         function file2() {
11             var data=new FormData();
12             data.append('file_key',document.getElementById('img').files[0]);
13 
14             var xhr = new XMLHttpRequest();
15             xhr.onreadystatechange=function () {
16                 if (xhr.readyState==4 ){
17                     //服务端返回数据接受完毕
18                     console.log(xhr.responseText)
19                 }
20             };
21 
22            xhr.open('POST','{% url "Ajax2" %}');
23             xhr.send(data);
24         }
25 
26 
27     </script>
JS方式(二)
 1     <h4>方式三:AJAX "伪造"</h4>
 2     <div>
 3         <h6>基于Iframe+Form表单【上传文件】</h6>
 4         <iframe id="iframe2" name="frame_file" style="display: none"></iframe>
 5         <form id="fm2" action="{% url 'Ajax2'%}" method="post" target="frame_file" enctype="multipart/form-data">
 6             <input type="file" name="img">
 7             <a class="abtn" onclick="tsFile()">伪造AJAX提交</a>
 8         </form>
 9     </div>
10 
11     <script src="/static/js/jquery-3.1.1.js"></script>
12     <script>
13 
14         function reload2() {
15                 //js
16                 console.log(this.contentWindow.document.body.innerHTML);
17                 //jquery
18                 console.log($(this).contents().find('body').html());
19                 //.................................................................
20                 var content = this.contentWindow.document.body.innerHTML;
21                 var obj= JSON.parse(content);
22                 console.log(obj)
23             }
24 
25         function tsFile() {
26             document.getElementById('iframe2').onload=reload2;
27             document.getElementById("fm2").submit();
28         }
29 
30     </script>
Iframe+Form方式(三)

 Iframe+From方式拓展:头像替换等

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7         .abtn{
 8             display: inline-block;
 9             padding: 5px 10px;
10             background-color: #cccccc;
11             color: white;
12         }
13         .abtn:hover{
14             background-color: red;
15         }
16     </style>
17 </head>
18 <body>
19         <div>
20             <h6>基于Iframe+Form表单【上传文件】</h6>
21             <iframe id="iframe2" name="frame_file" style="display: none"></iframe>
22             <form id="fm2" action="{% url 'upload_img'%}" method="post" target="frame_file" enctype="multipart/form-data">
23                 <input type="file" name="file_img" onchange="UploadFile()">
24             </form>
25             <h6>预览</h6>
26             <div id="preview">
27 
28             </div>
29         </div>
30 
31    <script src="/static/js/jquery-3.1.1.js"></script>
32     <script>
33         function reloadIframe() {
34                 //js
35                 //console.log(this.contentWindow.document.body.innerHTML);
36                 //jquery
37                 //console.log($(this).contents().find('body').html());
38                 //.................................................................
39                 var content = this.contentWindow.document.body.innerHTML;
40                 var obj= JSON.parse(content);
41                 var tag=document.createElement('img');
42                 tag.src=obj.data;
43                 $('#preview').empty().append(tag);
44             }
45         function UploadFile() {
46             document.getElementById('iframe2').onload=reloadIframe;
47             document.getElementById("fm2").submit();
48         }
49     </script>
50 </body>
51 </html>
upload.html
 1 from django.shortcuts import render,HttpResponse
 2 import json,os,uuid
 3 
 4 def upload(req):
 5 
 6     return render(req, "Ajax01/url/upload.html")
 7 
 8 
 9 def upload_img(req):
10     ret={"status":True,"data":None,"message":None}
11     obj = req.FILES.get('file_img')
12     nid = str(uuid.uuid4())
13     file_path = os.path.join('static/img', nid+'-'+obj.name)
14     f=open(file_path,'wb')
15     for line in obj.chunks():
16         f.write(line)
17     f.close()
18 
19     ret["data"]='http://127.0.0.1:8000/'+file_path
20     ret["message"]=200
21     return HttpResponse(json.dumps(ret))
views.py

 Jsonp:跨域请求

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <div id="content"></div>
 9     <input type="button" value="本地发送1" onclick="submitJsonp1()">
10     <input type="button" value="跨域发送2" onclick="submitJsonp2()">
11     <input type="button" value="跨域发送3" onclick="submitJsonp3()">
12     <input type="button" value="跨域发送4" onclick="submitJsonp4()">
13     <script src="/static/js/jquery-3.1.1.js"></script>
14     <script>
15         function submitJsonp1() {
16             $.ajax({
17                 url:'{% url "jsonp_a" %}',
18                 type:'GET',
19                 data:{'nid':2},
20                 success:function (arg) {
21                     $("#content").html(arg)
22                 }
23             })
24         }
25 
26         function submitJsonp2() {
27             var tag = document.createElement('script');
28             tag.src = 'http://127.0.0.1:8080/jsonp1/';
29             document.head.appendChild(tag);
30             document.head.removeChild(tag);
31         }
32 
33         function fuck(arg) {
34             $("#content").html(arg)
35         }
36 
37         function submitJsonp3() {
38             var tag = document.createElement('script');
39             tag.src = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403';
40             document.head.appendChild(tag);
41             document.head.removeChild(tag);
42         }
43 
44         function list(arg) {
45             console.log(arg)
46         }
47 
48         function submitJsonp4() {
49             $.ajax({
50                 url:'http://127.0.0.1:8080/jsonp1/',
51                 type:'GET',
52                 dataType:'jsonp',
53                 jsonp: 'callback',
54                 jsonpCallback: 'func'
55             })
56         }
57         
58         function func(arg) {
59             console.log(arg)
60         }
61     </script>
62 </body>
63 </html>
Jsonp
1 from django.shortcuts import render,HttpResponse
2 
3 # Create your views here.
4 
5 def jsonp1(req):
6     name=req.GET.get('callback')
7     print(name)
8     return HttpResponse('%s("跨域返回的数据");'%(name))
View Code

 

posted @ 2018-07-07 15:28  我在地球凑人数的日子  阅读(84)  评论(0)    收藏  举报