且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[django1.2+python2.7]ajax异步post数据,出现Forbidden的错误

更新时间:2022-09-02 11:24:10

假设我们现在需要ajax异步post数据到服务进行处理,下面是客户端的javascript代码。

 


  1. $("#ajaxpost").click(function(){ 
  2.         data=$('form').serializeArray(); 
  3.         data=$.toJSON(data); 
  4.         //alert(data); 
  5.          
  6.         $.ajax({ 
  7.             url:"/ajax_post/"
  8.             type:"POST"
  9.             contentType:"application/json; charset=utf-8"
  10.             //dataType:"json", 
  11.             data:data, 
  12.             success:function(data, textStatus, jqXHR){ 
  13.                 alert(decodeURIComponent(data)); 
  14.             }, 
  15.             error:function(jqXHR, textStatus, errorThrown){ 
  16.                 alert(textStatus); 
  17.                 alert(errorThrown); 
  18.             } 
  19.         }); 
  20.          
  21.          
  22.         return false
  23.          
  24.          
  25.     }); 

下面是服务端view的处理代码

 


  1. def ajax_post(request): 
  2.     if request.is_ajax() and request.method=="POST"
  3.         message="hello, ajax",request.raw_post_data 
  4.         json_data=simplejson.loads(request.raw_post_data) 
  5.         message=json_data 
  6.          
  7.     else
  8.         message="hello" 
  9.     return HttpResponse(message) 

完成之后,进行测试,发现弹出了错误对话框,而不是正确的对话框。

对话框提示内容

“FORBIDDEN”

解决办法是在python的view方法前面添加一个decorater

[@csrf_exempt]

 


  1. @csrf_exempt 
  2. def ajax_post(request): 
  3.     if request.is_ajax() and request.method=="POST"
  4.         message="hello, ajax",request.raw_post_data 
  5.         json_data=simplejson.loads(request.raw_post_data) 
  6.         message=json_data 
  7.         #message=json_data['data'] 
  8.     else
  9.         message="hello" 
  10.     return HttpResponse(message) 

关于CSRF(Cross Site Request Forgery)的一些内容可以参考官方文档:

https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/




本文转自 virusswb 51CTO博客,原文链接:http://blog.51cto.com/virusswb/796649,如需转载请自行联系原作者