一、Ajax简介
ajax不是新的编程语言,而是一种使用现有标准的新方法。
ajax最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
二、Ajax基本使用
2.1提交url
- views.py
def index(request):
return render(request,'index_new.html')
def ajax_header(request):
return HttpResponse("ok")
- index_new.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
<h1>ajax url提交</h1>
<button class="ajax">ajax提交</button>
<script>
(".ajax").click(function () {.ajax({
url: "/ajax_header/",
type: "get",
success: function (res) {
console.log(res)
}
})
})
</script>
</body>
</html>
2.2提交post方式
- views.py
def ajax_post(request):
if request.method == 'POST':
print(request.POST)
return HttpResponse("test")
- index_new.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
{% csrf_token %}
<h1>ajax post提交</h1>
<button class="ajax_post">ajax_post提交</button>
<script>
(".ajax_post").click(function () {.ajax({
url: "/ajax_post/",
type: "post",
data: {
name: "aaa",
addr: "bbb",
csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val()
},
success:function (res) {
console.log(res)
}
})
})
</script>
</body>
</html>
后端打印结果如下:
<QueryDict: {'name': ['aaa'], 'addr': ['bbb'], 'csrfmiddlewaretoken': ['q7iua6n9M26h6a1uhBk3uwoO1dC4aF2wQq9IX0LIBcMd1ZEdEMmqCkhGSopSpEkh']}>
2.3 json获取数据
- views.py
import json
def ajax_post(request):
if request.method == 'POST':
print(request.POST)
dic_a = {}
dic_a["id"] = 50
dic_a["name"] = "张三"
dic_a["addr"] = "北京"
data = json.dumps(dic_a)
return HttpResponse(data)
- html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
{% csrf_token %}
<hr>
<h1>ajax json获取数据</h1>
<button class="ajax_json">ajax_json</button>
<script>
(".ajax_json").click(function () {.ajax({
url: "/ajax_post/",
type: "post",
data: {
name: "aaa",
addr: "bbb",
csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
},
success:function (res) {
json_respose=JSON.parse(res)
console.log(json_respose)
}
})
})
</script>
</body>
</html>
留言