2、AJAX的引入
自己根据上面程序封装写的包(js文件格式)
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !=='')
{
var cookies = document.cookie.split(';');
for (var i = 0;i < cookies.length;i++)
{
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0,name.length + 1) === (name + '='))
{
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend:function (xhr,settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader('X-CSRFToken',csrftoken);
}
}
});
Ajax的方法
若数据中含有列表等多层数据需要traditional:True
几个示例:
HTML:
test
{% load static %}
{#数学运算#}
+
=
{#删除弹出提示#}
Panel title
{#登陆验证,光标移走弹出提示#}
JS文件:
1、计算器:
py代码:
def index(request):
i1 = int(request.GET.get('i1'))
i2 = int(request.GET.get('i2'))
return HttpResponse(i1+i2)
JS代码:
$("#b1").on("click",function () {
var i1 = $('#i1').val();
var i2 = $('#i2').val();
$.ajax({
url:"/index/",
type:'get',
data:{'i1':i1,'i2':i2},
success:function (arg) {
$('#i3').val(arg);
跳转
location.href = 'http://www.baidu.com';
查看数据类型
console.log(typeof arg)
}
})
})
2、反序列化数据
py代码:
from django.core import serializers
def xulie(request):
ret = models.Book.objects.all()
# 将ret转换成json数据格式
s = serializers.serialize("json",ret)
return HttpResponse(s)
JS代码:
$("#b1").on("click",function () {
$.ajax({
url:"/index/",
type:"get",
dataType:"json",
data:{"name":"李","age":11,"data":JSON.stringify([1,2,3])},
success:function (arg) {
{#反序列化数据#}
var data = JSON.parse(arg);
if(data.status === 0) {
{#请求成功#}
alert(data.data);
}
else {
{#请求失败#}
alert(data.error);
}
}
});
});
3、删除弹出提示框
JS代码:
$(".del").on('click',function () {
swal({title:'标题',
text:'内容',
type:'success',
showCancelButton: true,
confirmButtonClass:'btn-danger',
confirmButtonText:'确认',
cancelButtonText: '取消',
closeOnConfirm: false
});
});
4、登陆验证,光标移走弹出提示
py代码:
def logincheck(request):
if request.method == 'POST':
name = request.POST.get('name')
print(name)
ret = models.UserInfo.objects.filter(name=name)
print(ret)
if ret:
msg = '用户已存在'
else:
msg = '用户可用'
return HttpResponse(msg)
JS代码:
$('#i4').blur(function () {
var $this = $(this);
var input_date = $this.val();
console.log(input_date);
{#去掉input框后边的内容#}
$('#erro').text('');
$.ajax({
url:"/logincheck/",
type:'POST',
data:{'name':input_date},
success:function (arg) {
{#创建一个span标签#}
var spanEle = document.createElement('span');
spanEle.innerText = arg;
$(spanEle).css("color","red");
{#将span添加到输入框后边#}
$this.after(spanEle);
console.log(arg);
$('#erro').text(arg);
}
})
})