ajax
格式
1 $.ajax({ 2 url: '/add_classes.html', #提交地址,数据发送,在视图函数做操作 3 type: 'POST', #提交方式 4 data: {'username':'root','password': '123'}, #提交数据 5 success:function(arg){ 6 // 回调函数,arg是服务端返回的数据 7 } 8 })
traditional
发送数据时:data中的值v
a. 只是字符串或数字
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':'v1'},
dataType: 'JSON', //相当于执行var arg = JSON.parse(arg)
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. 传字典
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1': JSON.stringify({}) },
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})
- var data = $('#fmForm表单的ID').serialize();
//$('#fm').serialize() 获取表单内所有要提交的数据,不用再一个一个找
$.ajax({
data: $('#fm').serialize()
})
事件委托
$('要绑定标签的上级标签').on('click','要绑定的标签',function(){})
$('要绑定标签的上级标签').delegate('要绑定的标签','click',function(){})
简单示例
1 <input type="text" id="v1" placeholder="数字">+ 2 <input type="text" id="v2" placeholder="数字"> 3 <span onclick="sub()">等于</span> 4 <input type="text" id="v3"> 5 6 <script> 7 function sub() { 8 var v1=$('#v1').val(); 9 var v2=$("#v2").val(); 10 $.ajax({ 11 url:'/ajax3.html', 12 type:'POST', 13 data:{'v1':v1,'v2':v2}, 14 success:function (arg) { 15 console.log(arg); 16 $('#v3').val(arg); 17 //window.location.reload();//刷新页面 18 } 19 }) 20 } 21 </script>
1 def ajax3(request): 2 v1 = request.POST.get('v1') 3 v2 = request.POST.get('v2') 4 try: 5 v3 = int(v1)+int(v2) 6 except: 7 v3 = '输入有误' 8 9 return HttpResponse(v3) 10 11 url.py: 12 url(r'^ajax3.html$', ajax.ajax3),
示例2
<table> <thead></thead> <tbody> {% for row in obj %} <tr nid="{{ row.id }}"> <td> <a href="/....">删除</a> |<a href="" onclick="delstudent(this)">Ajax删除</a> |<a href="/....">编辑</a> </td> </tr> {% endfor %} </tbody> </table> ================================= function delstudent(ths) { var nid = $(ths).parent().parent().attr('nid');//根据当前标签的属性找到其在数据库中的ID $.ajax({ url:'/ajax4.html', type:'GET', data:{nid:nid}, //把获取到的ID传给后台,定义试图函数从数据库删除 success:function (arg) { if(arg == '成功'){ //window.location.reload() $(ths).parent().parent().remove(); //js删除,不刷新页面 ,把当前标签(ths)的父标签的父标签删除 }else{ alert(arg); } } }) }
from app01 import models def ajax4(request): msg = '成功' try: nid = request.GET.get('nid') models.Student.objects.filter(id=nid).delete() except Exception as e: msg = e return HttpResponse(msg) url(r'^ajax4.html$', ajax.ajax4),
上传图片:
1、ajax上传需要借助FormData对象
2、$("#fm").serializeArray(); 获取id为fm的form表单内除文件对象之外的数据,返回一个数组。
3、获取文件对象的方法:dom对象+.files[0]。 e.g. $("#avatar")[0].files[0]
4、后台request.FILES.get()获取文件对象
5、contentType: false, //不处理数据
processData: false, //不设置内容类型
var form_data = new FormData();
// 获取form表单内文本数据
var text_data = $("#fm").serializeArray();
$.each(text_data, function (index, data) {
form_data.append(data.name, data.value)
});
form_data.append("avatar", $("#avatar")[0].files[0]);
$.ajax({
url: "",
type: "post",
contentType: false,
processData: false,
data: form_data,
success: function (data) {
console.log(data);
}
d56
ret={ }
后台字典等非字符串类型转换为字符串:json.dumps(ret) 转回原类型:json.loads()
前段字典等非字符串类型转换为字符串:JSON.stringify(ret) 转回原类型:JSON.parse()
导入CSS -- <link rel="stylesheet" href="/......" />
导入JS,JQUERY --- <script src="/......"></script>
自执行函数 :写在<script>标签的最上边,页面加载完毕就执行
$(function () {
bindEvent();
//执行什么操作/函数等
});
$('#btnSave').click(function () { //找id绑定事件 var postData = {}; $('#addModal').find('input,select').each(function () { //找id,find()子子孙孙'input,select'标签,each:每一个都执行该函数 var v = $(this).val(); //$(this):函数操作的'input或select'标签 var n = $(this).attr('name'); //.val():标签的value值 //.attr('name'):标签的name属性 如:<select name="cls_id"> if(n=='gender'){ //radio框有checked属性,可以用prop('checked')设置选中 if($(this).prop('checked')){ // //对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。 postData[n] = v; } }else{ postData[n] = v; } });
创建标签
var tdAge = document.createElement('td');
tdAge.innerHTML = postData.age;
$(tr).append(tdAge);
拼接字符串
var tdClass = document.createElement('td');
var text = $('select[name="cls_id"]').find('option[value="'+ postData.cls_id +'"]').text();
tdClass.innerHTML = text;
$(tr).append(tdClass);
二
d62
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .btn{ 8 display: inline-block; 9 padding: 5px 10px; 10 background-color: plum; 11 } 12 </style > 13 </head> 14 <body> 15 <h1>Ajax全套</h1> 16 <h3>1、AjaxGET请求</h3> 17 <div> 18 <a class="btn" onclick="AjaxSubmit1()">$.ajaxGET</a> 19 <a class="btn" onclick="AjaxSubmit2()">原生ajaxGET</a> 20 </div> 21 <h3>2、AjaxPOST请求</h3> 22 <div> 23 <a class="btn" onclick="AjaxSubmit3()">$.ajaxPOST</a> 24 <a class="btn" onclick="AjaxSubmit4()">原生ajaxPOST</a> 25 </div> 26 <h3>3、伪造Ajax请求</h3> 27 <div> 28 <a class="btn" onclick="AjaxSubmit5()">伪造ajax</a> 29 </div> 30 <div> 31 <p class="btn">IFrame</p> 32 <div><input id="url" placeholder="请输入url"><a onclick="ifm()">dian</a></div> 33 <iframe id="ifm" style="height: 50px;width: 200px" src=""></iframe> 34 </div> 35 <div> 36 37 <h3 class="btn">IFrame+form</h3> 38 <!--IFrame的name和form的target--> 39 <iframe id="ifm" name="ifrm"></iframe> 40 <form id="fm" action="/ajax1.html" method="post" target="ifrm"> 41 <input name="root" value="111111"> 42 43 <a onclick="AjaxSubmit5()">提交</a> 44 </form> 45 </div> 46 <h3>4、文件上传</h3> 47 <input type="file" id="img" /> 48 <a class="btn" onclick="AjaxSubmit6();">$Ajax上传</a> 49 <a class="btn" onclick="AjaxSubmit7();">原生Ajax上传</a> 50 <div> 51 <iframe id="ifm1" name="ifrm1"></iframe> 52 <form id="fm1" action="/ajax1.html" method="post" enctype="multipart/form-data" target="ifrm1"> 53 <input type="text" name="k1" /> 54 <input type="text" name="k2" /> 55 <input type="file" name="k3" /> 56 <a onclick="AjaxSubmit8()" class="btn">iframe上传</a> 57 </form> 58 </div> 59 60 61 62 <script src="/static/jquery-1.12.4.js"></script> 63 <script> 64 65 66 function ifm() { 67 var url=$('#url').val(); 68 $('#ifm').attr('src',url) 69 } 70 71 function AjaxSubmit1() { 72 $.ajax({ 73 url:'/ajax1.html', 74 type:'GET', 75 data:{'p':123}, 76 success:function (arg) { 77 78 } 79 }) 80 } 81 82 function AjaxSubmit2() { 83 var xhr=new XMLHttpRequest(); 84 //创建XMLHttpRequest对象,在JS里创建对象必须用new关键字 85 xhr.open('GET','/ajax1.html?p=123'); //创建链接(以GET方式,发送地址) 86 xhr.onreadystatechange = function () { 87 //回调函数 88 if(xhr.readyState == 4){ 89 //服务器端返回的数据接收完毕 90 var dat = xhr.responseText; //服务器端返回的数据 91 console.log(dat) 92 } 93 }; 94 xhr.send(null); //发送数据 95 } 96 97 function AjaxSubmit3() { 98 $.ajax({ 99 url:'/ajax1.html', 100 type:'POST', 101 data:{'p':456}, 102 success:function (arg) { 103 104 } 105 }) 106 } 107 108 function AjaxSubmit4() { 109 var xhr=new XMLHttpRequest(); 110 xhr.onreadystatechange = function () { 111 if(xhr.readyState == 4){ 112 var dat = xhr.responseText; 113 console.log(dat) 114 } 115 }; 116 xhr.open('POST','/ajax1.html'); 117 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); 118 //发送POST请求,必须有请求头,即上边一行 119 xhr.send('p=456'); //发送数据 120 } 121 122 function AjaxSubmit5() { 123 document.getElementById('ifm').onload=reloadIframe; 124 document.getElementById('fm').submit(); 125 } 126 function reloadIframe() { 127 // this=当前标签 128 //console.log(ths); 129 //console.log(ths.contentWindow); 130 //console.log(ths.contentWindow.document.body.innerHTML); 131 //console.log($(ths).contents().find('body').html()); 132 var content = this.contentWindow.document.body.innerHTML; 133 var obj = JSON.parse(content); 134 if(obj.status){ 135 alert(obj.message); 136 } 137 } 138 139 //FormData对象既能封装字符串内容又能封装文件对象 140 function AjaxSubmit6() { 141 //document.getElementById('img')[0] 142 //#前边是一个选择器对象,加上索引0表示上传的文件内容 143 var data = new FormData(); 144 data.append('k1','v1'); 145 data.append('k2','v2'); 146 data.append('k3',document.getElementById('img').files[0]); 147 148 $.ajax({ 149 url: '/ajax1.html', 150 type: 'POST', 151 data:data, 152 success:function (arg) { 153 console.log(arg) 154 }, 155 processData: false, // tell jQuery not to process the data 156 contentType: false // tell jQuery not to set contentType 157 158 }) 159 } 160 161 function AjaxSubmit7() { 162 var data = new FormData(); 163 data.append('k1','v1'); 164 data.append('k2','v2'); 165 data.append('k3',document.getElementById('img').files[0]); 166 167 var xhr = new XMLHttpRequest(); 168 xhr.onreadystatechange = function () { 169 if(xhr.readyState == 4){ 170 // 接收完毕服务器返回的数据 171 console.log(xhr.responseText); 172 173 } 174 }; 175 xhr.open('POST','/ajax1.html'); 176 xhr.send(data); 177 } 178 179 function AjaxSubmit8() { 180 document.getElementById('ifm1').onload=reloadIframe1; 181 document.getElementById('fm1').submit(); 182 } 183 function reloadIframe1() { 184 var content = this.contentWindow.document.body.innerHTML; 185 var obj = JSON.parse(content); 186 //if(obj.status){ 187 // alert(obj.message); 188 //} 189 } 190 191 </script> 192 </body> 193 </html>
def index(request):
return render(request,'index.html')
def ajax1(request):
print(request.GET)
print(request.POST)
print(request.FILES)
return HttpResponse(".....")
<div> <a class="btn" onclick="AjaxSubmit1()">$.ajaxGET</a> <a class="btn" onclick="AjaxSubmit2()">原生ajaxGET</a> </div> <script> function AjaxSubmit1() { $.ajax({ url:'/ajax1.html', type:'GET', data:{'p':123}, success:function (arg) { } }) } function AjaxSubmit2() { var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象,在JS里创建对象必须用new关键字 xhr.open('GET','/ajax1.html?p=123'); //创建链接(以GET方式,发送地址) xhr.onreadystatechange = function () { //回调函数 if(xhr.readyState == 4){ //服务器端返回的数据接收完毕 var dat = xhr.responseText; //服务器端返回的数据 console.log(dat) } }; xhr.send(null); //发送数据 } </script>
<div> <a class="btn" onclick="AjaxSubmit3()">$.ajaxPOST</a> <a class="btn" onclick="AjaxSubmit4()">原生ajaxPOST</a> </div> <script> function AjaxSubmit3() { $.ajax({ url:'/ajax1.html', type:'POST', data:{'p':456}, success:function (arg) { } }) } function AjaxSubmit4() { var xhr=new XMLHttpRequest(); xhr.onreadystatechange = function () { if(xhr.readyState == 4){ var dat = xhr.responseText; console.log(dat) } }; xhr.open('POST','/ajax1.html'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); //发送POST请求,必须有请求头,即上边一行 xhr.send('p=456'); //发送数据 } </script>
<div> <!--IFrame的name和form的target--> <iframe id="ifm" name="ifrm"></iframe> <form id="fm" action="/ajax1.html" method="post" target="ifrm"> <input name="root" value="111111"> <a onclick="AjaxSubmit5()" class="btn" >提交</a> </form> </div> <script> function AjaxSubmit5() { document.getElementById('ifm').onload=reloadIframe; document.getElementById('fm').submit(); } function reloadIframe() { // this=当前标签 //console.log(ths); //console.log(ths.contentWindow); //console.log(ths.contentWindow.document.body.innerHTML); //console.log($(ths).contents().find('body').html()); var content = this.contentWindow.document.body.innerHTML; var obj = JSON.parse(content); if(obj.status){ alert(obj.message); } } </script>
var content = this.contentWindow.document.body.innerHTML;
//iframe是一个Html页面,相当于form表单把数据提交到了另一个Html,
//这一步就是去iframe的html里取提交的内容
<input type="file" id="img" /> <a class="btn" onclick="AjaxSubmit6();">$Ajax上传</a> <a class="btn" onclick="AjaxSubmit7();">原生Ajax上传</a> <script> //借助FormData对象 //FormData对象既能封装字符串内容又能封装文件对象 function AjaxSubmit6() { //document.getElementById('img')[0] //#前边是一个选择器对象,加上索引0表示上传的文件内容 var data = new FormData(); data.append('k1','v1'); data.append('k2','v2'); data.append('k3',document.getElementById('img').files[0]); $.ajax({ url: '/ajax1.html', type: 'POST', 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 }) } function AjaxSubmit7() { var data = new FormData(); data.append('k1','v1'); data.append('k2','v2'); data.append('k3',document.getElementById('img').files[0]); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if(xhr.readyState == 4){ // 接收完毕服务器返回的数据 console.log(xhr.responseText); } }; xhr.open('POST','/ajax1.html'); xhr.send(data); } </script>
<div> <iframe id="ifm1" name="ifrm1"></iframe> <form id="fm1" action="/ajax1.html" method="post" enctype="multipart/form-data" target="ifrm1"> <input type="text" name="k1" /> <input type="text" name="k2" /> <input type="file" name="k3" /> <a onclick="AjaxSubmit8()" class="btn">iframe上传</a> </form> </div> <script> function AjaxSubmit8() { document.getElementById('ifm1').onload=reloadIframe1; document.getElementById('fm1').submit(); } function reloadIframe1() { var content = this.contentWindow.document.body.innerHTML; var obj = JSON.parse(content); //if(obj.status){ // alert(obj.message); //} } </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .btn{ display: inline-block; padding: 5px 10px; background-color: plum; } </style> </head> <body> <div> <iframe id="ifm1" name="ifrm1" style="display: none"></iframe> <form id="fm1" action="/upload_img.html" method="post" enctype="multipart/form-data" target="ifrm1"> <input type="file" name="k3" onchange="uploadFile();"/> </form> <h3>预览</h3> <div id="preview"></div> </div> <script src="/static/jquery-1.12.4.js"></script> <script> function uploadFile() { document.getElementById('ifm1').onload=reloadIframe1; document.getElementById('fm1').submit(); } function reloadIframe1() { var content = this.contentWindow.document.body.innerHTML; var obj = JSON.parse(content); var tag = document.createElement('img'); tag.src = obj.data; $('#preview').empty().append(tag); } </script> </body> </html>
def upload(request): return render(request,'upload.html') def upload_img(request): import os,json import uuid # 给文件名增加前缀,防止不同用户上传相同文件名冲突 nid = str(uuid.uuid4()) ret = {'status': True, 'data': None, 'message': None} obj = request.FILES.get('k3') file_path = os.path.join('static', nid + obj.name) f = open(file_path, 'wb') for line in obj.chunks(): f.write(line) f.close() ret['data'] = file_path return HttpResponse(json.dumps(ret))
jsonp
浏览器具有同源策略,Ajax跨域请求服务器能正常接收,但会被浏览器阻止
Ajax发送跨域请求,被请求的服务器将返回信息放在一个没有定义逻辑的函数的参数,请求方收到后定义同名函数,把返回的信息放在参数上操作
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="content"></div> <input type="button" value="发送3" onclick="submitJsonp3();" /> <input type="button" value="发送4" onclick="submitJsonp4();" /> <script src="/static/jquery-1.12.4.js"></script> <script> function submitJsonp3() { var tag = document.createElement('script'); tag.src = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403'; document.head.appendChild(tag); document.head.removeChild(tag); } function list(arg) { console.log(arg); } function submitJsonp4() { $.ajax({ url: '请求地址', type: 'GET', //jsonp只能发GET请求 dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'func' }) } function func(arg) { console.log(arg); } </script> </body> </html>
def fanhui(request): name = request.GET.get('callback') #获取前端Ajax请求使用的函数名 return HttpResponse("%s('返回的内容');" %name)