1、准备
1.1 设置静态文件路径
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
1.2 添加路由
1.3 写前端文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
<style>
.btn {
background-color: antiquewhite;
padding: 5px 20px;
margin: 20px;
color: black;
}
</style>
</head>
<body>
<h1>Index</h1>
<a class="btn" onclick="ajax1()">点我</a><br>
<a class="btn" onclick="ajax2()">点我</a><br>
<a class="btn" onclick="ajax3()">点我</a><br>
<a class="btn" onclick="ajax4()">点我</a><br>
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
function ajax1() {
$.ajax({
url: "/ajax1",
type: "GET",
data: {"abc": 123},
success: function (arg) {
console.log(arg)
}
})
}
function ajax2() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
console.log(xhr.responseText);
}
};
xhr.open('GET', '/ajax2?p=123');
xhr.send(null)
}
function ajax3() {
$.ajax({
url: "/ajax1",
type: "POST",
data: {"abc": 123},
success: function (arg) {
console.log(arg)
}
})
}
function ajax4() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
console.log(xhr.responseText);
}
};
xhr.open('POST', '/ajax2');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); // 不加这句,django只会在request.body中添加数据,request.POST中没有数据
xhr.send("p=123");
}
</script>
</body>
</html>
2、Ajax方式
2.1 GET
2.2 POST
3、XMLHttpRequest方式
3.1 GET
3.2 POST
由于jquery文件也有好几M,所以在手机端最好使用XMLHttpRequest方式。