$('#ajax_submit').click(function () { $.ajax({ 'url':'/app_ajax', 'type':'post', 'data':$("#f1").serialize(), #将一个form表单全部发送到后台 {# 'data':{'app_name':'123','host_lists':[1,2,3,4]},#} traditional:true, #支持能发送数组格式到后台 dataType:'JSON', #不用将后台返回的json格式解析,省去obj = JSON.parse(data) success:function (obj) { if(obj.status=='true'){ $('#msg').removeClass('hide').text(obj.data); {# location.reload();#} }else { $('#msg').removeClass('hide').text(obj.error); } }, error:function () { #只有后台出的错误 没有被捕获到,或不识别才执行 alert('undifine error'); } }) 后台:
def app_ajax(request):
ret = {"status":"true","data":"none","error":"none"}
try:
name = request.POST.get('app_name')
hosts = request.POST.getlist('host_lists')
if name and hosts:
obj = models.app.objects.create(name=name)
obj.r.add(*hosts)
ret['data']='success'
else:
ret['status']='false'
ret['error']='error'
except Exception as e:
pass
return HttpResponse(json.dumps(ret))