Django配合使用Jquery post方法

Django使用jQuery的post方法需要解决两个问题:

1.Django中为了防止跨站请求,在post提交时都会带上csrf_token,利用Jquery进行post请求也需要;否则就会出现403 forbidden错误

2.在Django的view中,如何返回json串给jquery

view方法如下所示:

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. def get_productitem(request,*callback_args):  
  2.     productid = request.POST.get('productid')  
  3.     rtn = dict()  
  4.     if productid is not None:  
  5.         productitemlist = Producitem.objects.filter(productid=productid).all()  
  6.         for productitemitem in productitemlist:  
  7.             rtn[productitemitem.id] = "%s(%s)"%(productitemitem.itemname,productitemitem.itemversion)  
  8.     return HttpResponse(json.dumps(rtn),mimetype='application/json')  


template中的jquery请求方法如下所示:

[javascript] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. $.ajaxSetup({  
  2.   beforeSend: function(xhr, settings){   
  3.       var csrftoken = $.cookie('csrftoken');   
  4.       xhr.setRequestHeader("X-CSRFToken", csrftoken);   
  5.   }  
  6. });  
  7. changeProduct();  
  8. function changeProduct(){  
  9.     var productid = $("#productid").val();  
  10.     if(productid == null){  
  11.         return;  
  12.     }  
  13.     jQuery.post('/getProductitem',{  
  14.         productid:productid  
  15.     },function(dat){  
  16.         var productitemid = $("#productitemid");  
  17.         var options = '';  
  18.         for(jsonkey in dat){  
  19.             options += "<option value='" + jsonkey + "'>" + dat[jsonkey] + "</option>";  
  20.         }  
  21.         if(options != ''){  
  22.             productitemid.html(options);  
  23.         }     
  24.     });  
  25. }  

记得,如果要是用$.cookie方法,需要引入jquery.cookie.js文件。

同时注意在jquery所在页面的form表单里加入{% csrf_token %},否则Jquery post的X-CSRFToken头部为空。

原文地址:https://www.cnblogs.com/AmilyWilly/p/6247764.html