Django--ajax
需求:
前端通过ajax把数据提交到后台
1、单条提交
html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | < body > < input type = "button" value = "ajax提交" onclick = "AjaxSubmit();" > <!--数据应该从标签里获取,这里就不做了,设定了几个值提交。--> < script src = "/static/js/jquery-2.1.4.min.js" ></ script > < script type = "text/javascript" > function AjaxSubmit(){ var host='1.1.1.1'; var port='111'; $.ajax({ url:'/ajax_data/', type:'POST', data:{h:host,p:port}, success: function (arg) { } }); } </ script > </ body > |
urls.py
1 2 3 4 5 | from app01 import views urlpatterns = [ url(r '^admin/' , admin.site.urls), url(r '^ajax_data/' , views.ajax_data), ] |
app01/views.py
1 2 3 | def ajax_data(request): print request.POST return HttpResponse( 'ok' ) |
IDE
2、数组提交
html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | < input type = "button" value = "ajax提交" onclick = "AjaxSubmitSet();" > <!--数据应该从标签里获取,这里就不做了,设定了几个值提交。--> < script src = "/static/js/jquery-2.1.4.min.js" ></ script > < script type = "text/javascript" > function AjaxSubmitSet(){ var hosts=[{'ip':'1.1.1.1','port':'111'},{'ip':'2.2.2.2','port':'222'}]; $.ajax({ url:'/ajax_data_set/', type:'POST', data:{data:hosts}, success: function (arg) { } }); } </ script > |
urls.py
1 2 3 4 5 | from app01 import views urlpatterns = [ url(r '^admin/' , admin.site.urls), url(r '^ajax_data_set/' , views.ajax_data_set), ] |
app01/views.py
1 2 3 | def ajax_data_set(request): print request.POST return HttpResponse( 'ok' ) |
IDE
刷新页面,点击ajax提交按钮,IDE打印出了如下信息:
修改html中ajax提交方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function AjaxSubmitSet(){ var hosts=[{'ip':'1.1.1.1','port':'111'},{'ip':'2.2.2.2','port':'222'}]; $.ajax({ url:'/ajax_data_set/', type:'POST', tradition:true, data:{data:JSON.stringify(hosts)}, success: function (arg) { //返回值是字符串,把它先转化成字典 //相当于json.loads(),parseJSON将字符串转换成对象 var callback_dict= $.parseJSON(arg); if(callback_dict.status){ alert('成功'); }else{ alert(callback_dict.error); } } }); } |
IDE
这样的数据格式我们就方便取值了。
3、返回值
标准的输出:{status:‘true',error:''}
app01/views.py
1 2 3 4 5 6 7 8 9 | import json def ajax_data_set(request): ret = { 'status' : True , 'error' :""} #默认ajax成功返回的格式 try : #如果提交成功,打印提交的数据,返回ret print request.POST except Exception,e: #当出错异常,修改返回值 ret[ 'status' ] = False ret[ 'error' ] = str (e) return HttpResponse(json.dumps(ret)) #只能返回字符串 |
html中的ajax
1 2 3 4 5 6 7 8 9 10 | success: function (arg) { //返回值是字符串,把它先转化成字典 //相当于json.loads(),parseJSON将字符串转换成对象 var callback_dict= $.parseJSON(arg); if(callback_dict.status){ alert('成功'); }else{ alert(callback_dict.error); } } |
browser
制造异常app01/views.py
1 2 | try : print request.PO #故意写错,抛出异常。 |