Ajax基础
初始ajax
1.ajax代码
1 $('#ajax_submit').click(function () { 2 $.ajax({ 3 url:"/app02/test_ajax/", 4 type:'POST', 5 data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()}, 6 success:function (data) { 7 if (data=='ok'){ 8 location.reload() 9 }else{ 10 alert(data) 11 } 12 } 13 }) 14 })
后台代码
def test_ajax(request): h = request.POST.get('hostname') i = request.POST.get('ip') p = request.POST.get('port') b = request.POST.get('b_id') if len(h)>5 and h : models.Host.objects.create(hostname=h, ip=i, port=p, b_id=b) return HttpResponse('ok') else: return HttpResponse('太短了')
$.ajax({ url: '/host', type: "POST", data: {'k1': 123,'k2': "root"}, success: function(data){ // data是服务器端返回的字符串 var obj = JSON.parse(data); } })
建议:永远让服务器端返回一个字典
return HttpResponse(json.dumps(字典))
3.ajax其他提交方式
$('#add_submit_ajax').click(function () { $.ajax({ url:'/app02/ajax_add_app/', {#data:{'user':123,'host_list':[1,2,3,4]},#} data:$('#add_form').serialize(), type:'POST', dataType:'JSON',//自动将传过来的字符串转换成JSON对象 traditional: true,//host_list不是字符串和数字,后台会报None。jQuery中traditional会将列表传过去 success:function (obj) { console.log(obj) if(obj.status){ console.log('增加成功') location.reload() }else { $('#erro_msg').text(obj.error) console.log('xx') } }, error:function () { } }) })
4.发送ajax之前执行此函数,全局配置
$(function(){
$.ajaxSetup({
beforeSend: function(xhr,settings){
xhr.setRequestHeader('X-CSRFtoken', $.cookie('csrftoken'));
}
});
$('#btn1').click(function () {
$.ajax({
url: '/app03/login/',
type:"GET",
data: {'user': 'root', 'pwd': '123'},
// headers: {'X-CSRFtoken': $.cookie('csrftoken')},
success:function(arg){
}
})
});
})