/**
* 此事例代码演示做基础的方式书写的ajax请求,也是实际开发中最常见的写法
*/
//页面初始化之后的执行函数,在页面中的html和js代码加载完成之后触发
在Django的模板中加载静态文件 {% load staticfiles %}
使用jquery时必须引用jquery库,因为jQuery是对JavaScript的封装,必须引用,直接写原生JavaScript代码不用引用库 $ 美元符号是jquery的标志。
* 此事例代码演示做基础的方式书写的ajax请求,也是实际开发中最常见的写法
*/
//页面初始化之后的执行函数,在页面中的html和js代码加载完成之后触发
$(function(){
$('#btnGet').click(function(){ //get请求按钮点击之后触发
$.ajax({
type: "get", //请求方式
url: location.href, //此处填写你的请求接受地址
data: {}, //请求时发送给服务器端的数据,如果没有可以为空对象
dataType: "json",//请求数据的返回格式 一般使用json(常见的数据返回方式)
success: function (res) { //请求发送成功之后触发
console.log('success')
console.log(res)
},
error: function(err){ //请求失败之后触发
console.log('err')
console.log(err)
},
complete: function(data){ //请求完成之后触发不管成功和失败
console.log('complete')
console.log(data)
}
})
})
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
$('#btnPost').click(function(){//post请求按钮点击之后触发
$.ajax({
type: "post", //请求方式
url:location.href, //此处填写你的请求接受地址
data: {name:'Tom',age:18}, //请求时发送给服务器端的数据,如果没有可以为空对象
dataType: "json",//请求数据的返回格式 一般使用json(常见的数据返回方式)
success: function (res) { //请求发送成功之后触发
console.log('success')
console.log(res)
},
error: function(err){ //请求失败之后触发
console.log('err')
console.log(err)
},
complete: function(data){ //请求完成之后触发不管成功和失败
console.log('complete')
console.log(data)
}
})
})
})
注意:ajax请求的服务器端的视图函数:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Student
import json
# Create your views here.
def ajax(request):
student = {"birthday": "05-04", "name": "Gavin"}
content =json.dumps(student)
print content,type(content)
if request.is_ajax() and request.method == 'GET':
return HttpResponse(content, content_type='application/json')
elif request.is_ajax() and request.method == 'POST':
print "hello"
else:
return render(request,template_name='ajax.html')
判断请求是不是ajax请求用 request.is_ajax() 请求的方式:request.method
ajax请求 的响应数据内容的格式必须写:content_type='application/json'
在seting文件中设置:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
]
渲染模板:
{% load staticfiles %}
<html>
<head>
<title>ajax测试</title>
<script src= "{% static "js/jquery.min.js" %}"></script>
</head>
<body>
<input type="button" οnclick="send_request();" value="点击此处发送AJAX请求" /><br/>
<b>姓名:</b><span id="idName"></span><br/>
<b>生日:</b><span id="idBirthday"></span><br/>
</body>
<script type="text/javascript">
function send_request(){
$.get('/ajax/', function(data){
$("#idName").html(data.name);
$("#idBirthday").html(data.birthday);
});
}
</script>
<html>
在Django的模板中加载静态文件 {% load staticfiles %}
使用jquery时必须引用jquery库,因为jQuery是对JavaScript的封装,必须引用,直接写原生JavaScript代码不用引用库 $ 美元符号是jquery的标志。