191114Ajax.md
一、Ajax字符串、数字、布尔值类型与后端交互
- ajax提交
$.ajax({
url: '/del_student/',
type: 'GET',
data: {'nid': 2}, //此处数据类型是int
success: function (arg) {
var dict = JSON.parse(arg);
if(dict.status){
$('tr[nid="'+ rowId +'"]').remove();
}
$('#delModal').modal('hide');
}
})
- 接收
def del_student(request):
ret = {'status': True}
try:
nid = request.GET.get('nid')
models.Students.objects.filter(id=nid).delete()
except Exception as e:
ret['status'] = False
return HttpResponse(json.dumps(ret))
二、Ajax列表数据类型与后端交互
- ajax提交
$.ajax({
url: '/del_student/',
type: 'GET',
data: {'nid': [2,3,4,5]}, //此处数据类型是list
traditional: true //传数组需要加此项
success: function (arg) {
var dict = JSON.parse(arg);
if(dict.status){
$('tr[nid="'+ rowId +'"]').remove();
}
$('#delModal').modal('hide');
}
})
- 接收
def del_student(request):
ret = {'status': True}
try:
nid = request.GET.getlist('nid') #需要使用getlist接收
models.Students.objects.filter(id=nid).delete()
except Exception as e:
ret['status'] = False
return HttpResponse(json.dumps(ret))
Ajax POST提交只支持字符串、数字、数组,不支持字典类型数据
如果必须使用字典时可以转换为字符串:
data: {'k1': JSON.srtingify({'k2':'v2'})}