table of Contents
Django (七) --- AJAX
Introduction to AJAX
AJAX (Asynchronous Javascript And XML), translated into Chinese is 'asynchronous javascript and XML'
Using javascript language with the server asynchronous interaction , transmission of data to XML
AJAX biggest feature is, you can not reload the entire page in the case, and can exchange data with the server, and update parts of the page content
AJAX does not require any browser plug-ins, but allow the user needs to perform Javascript in your browser
Synchronous interaction: the client sends a request to the appropriate server to wait for the end, in order to issue a second request
Asynchronous interaction: After the client makes a request, without waiting for the end of the server response, it can issue a second request
ajax basic grammatical structures
is_ajax () determines whether the current request is ajax request, it returns a Boolean value
After using ajax, httpresponse not in action on the page, but do interact directly with ajax
$('#d4').on('click',function () {
$.ajax({
url:'', // 数据提交的后端地址 不写就是往当前页面提交 也可以写后缀 也可以写全称 跟actions一样
type:'post', // 提交方式 默认是get请求
data:{'i1':$('#d1').val(),'i2':$('#d2').val()}, // 提交的数据
success:function (data) { // 形参data就是异步提交之后后端返回结果
$('#d3').val(data) // 回调机制需要做的事情
}
})
})
Front and rear ends the transmission data encoding format
A data encoding format interaction between the front and rear ends, not for data back-end processing of different
Such as: request.POST request.FILES and both are used to obtain the data transmitted by the user
Encoding (suffix):
1. urlencoded
2. formdata(enctype)
3. application/json格式数据
The backend data transmission method:
1. a标签通过href携带参数 get请求
2. form表单 get/post
3. ajax get/post
transmitting the encoded form form data format
urlencoded for the goal of a single default encoding
urlencoded corresponding data format:
username=simple&password=123
For urlencoded django backend data, and automatically resolve the encapsulated request.POST
- When sending a file form form, encoding format is Content-Type: multipart / form-data;
django backend urlencoded long as the data format is satisfied, to automatically resolve the request.POST
If it is a file object, django backend will automatically identify and placed in request.FILES
- form form can not send data json format, if you want to send, only by means of ajax
transmitting the encoded data format ajax
Ajax three formats transmittable
1. urlencoded
2. formdata
3. application/json格式数据
By ajax contentType parameter, modify the coding format:
Converted into a data format json
contenType:'application/json
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
ajax default encoding format is urlencoded, rear django also parses the data into the request.POST
Note :
Front and rear ends when it comes to interactive data, format and coding format of the data must be consistent
Data transfer format ajax json
后端 前段
dumps stringify
loads parse
Transmission format data by json ajax, the data
Content-Type: application/json
$('#d1').click(function () {
$.ajax({
url:'',
type:'post',
contentType:'application/json', # 1.注意点1
data:JSON.stringify({'username':'jason','password':'123'}), # 2.注意点2
success:function (data) {
alert(123)
}
})
django json for before and after transmission over the data processing will not do
Request.body placed directly in the (json binary data)
Ajax data transfer files
New built-in objects by means of
the object which can carry data files also support common key-value pairs
$('#d1').click(function () {
// 先生成一个内置对象
var MyFormData = new FormData();
// 1. 先添加普通的键值
MyFormData.append('username','jason'); // 添加了一组普通的简直对
MyFormData.append('password','123');
// 2. 添加文件数据
MyFormData.append('myfile',$('#d2')[0].files[0]); // 如何获取input框中文件对象$('#d1')[0].files[0]
$.ajax({
url:'',
type:'post',
data:MyFormData, # 1
// 发送文件必须要指定的两个参数
contentType:false, // 不适用任何编码 MyFormData对象内部自带编码 django后端能够识别 #2
processData:false, // 不要处理数据 # 3
success:function (data) {
}
})
})
Serialization
The serialized data integration into one large dictionary, interactive data before and after the end of convenience, front and rear ends to achieve separation
from app01 import models
from django.core import serializers
# 序列化目的 将数据整合成一个大字典形式 方便数据的交互
def zzz(request):
user_queryset = models.User.objects.all()
# [{username:...,password:...,hobby:...,},{},{},{}]
# user_list = []
# for data in user_queryset:
# user_list.append(
# {'username':data.username,
# 'password':data.password,
# 'gender':data.get_gender_display(),
#
# }
# )
res = serializers.serialize('json',user_queryset)
return HttpResponse(res)