$('#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))