使用Django框架编写web项目时,在前端页面中使用jquery提交post请求,遇到到了一些问题,在此记录学习的过程
img.html
<!--加载文件-->
{% load staticfiles %}
<script type="text/javascript" src="{% static '/js/jquery-1.6.1.min.js' %}"></script>
<script type="text/javascript">
$(document).ready(function(){
//定义一个全局变量
var numb = 0;
$(".next_img").click(function(){
img_numb++;
var p_data = {'s_type':'1','numb': numb}
// 使用post提交
$.post("/show_home",p_data,function(img_url){
// 提交成功后的操作,img_url为返回参数
$("img").attr("src",img_url);
});
});
});
<a class="next_img">img</a>
<img style="height:668px;" src="/static/images/2.jpeg"/>
urls.py
from datamanage import views
urlpatterns = [
url(r'^show_home', views.show_home),
]
views.py
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_exempt
def show_home(request):
if request.POST:
s_ype = request.POST['s_type']
numb = request.POST['numb']
img_url = ''
return HttpResponse(img_url)
else:
return render(request, "img.html")
问题:
是Django在处理post请求时出现403错误
经过百度说有以下方法解决:
原文1:http://www.cnblogs.com/xtt-w/p/6232559.html
解决方法:
在settings.py里面的MIDDLEWARE_CLASSES中去掉“‘django.middleware.csrf.CsrfViewMiddleware’,”。
原文2:http://blog.youkuaiyun.com/sherry_rui/article/details/50523725
解决方法:
1.在发送post请求的html页面前加入{% csrf_token %} 如:
<form action="/login" method="post">
{% csrf_token %}
<input type="text" required="required" placeholder="用户名" name="u"/>
<input type="password" required="required" placeholder="密码" name="p"/>
<button class="but" type="submit">登录</button>
</form>
2.在处理post数据的view前加@csrf_exempt装饰符,如:
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_exempt
def profile_delte(request):
del_file=request.POST.get("delete_file",'')