django框架下用ajax提交不成功被403掉 求各位大神指导!!!

swjtutipo 2014-09-17 11:33:27
用django框架开发,前端用ajax提交数据到后台,一直提示403,被屏蔽掉了。form里面增加了{% csrf_token %},views.py里面增加了@csrf_protect 和context_instance=RequestContext(req),用FORM提交的方式是可以的。ajax中也增加了一段JS代码,但是仍然没办法提交,ajax可以get到后台的数据。
我写的一个简单的ajax DEMO:
var str = '{"name":"John"}';
var obj = $.parseJSON(str);

$.ajax({
type: "POST",
url: "/test/",
contentType: "application/json;charset=utf-8",
datatype: "json",
//data: JSON.stringify({
// 'ret': "ret"
//}),
data: obj,
async: false,
//cache: false,
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});
到底是怎么回事呢,是不是django框架下就不能用ajax提交数据了啊,有没有用ajax成功提交数据的demo可以参考一下,折腾好长时间了。
...全文
657 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
TKEngine 2015-03-11
  • 打赏
  • 举报
回复
你好,参考大家的做法,ajax post还是不成功,可以帮我看看是什么原因吗? teacherPaper.js function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } teacherPaper.html <script language="JavaScript" type="text/javascript" src="{% static 'js/jquery.js' %}"></script> <script language="JavaScript" type="text/javascript" src="{% static 'js/teacherPaper.js' %}"></script> <script> $(function() { $(".each-ch-del").click(function() { var eno_id = $(this).attr("id"); var eno_div = "#each-ch-"+eno_id; var pno = "0"+{{pno}}; $(eno_div).hide(); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ type: 'POST', url: '/exercise_system/teacher/paper/delete', data:{'delEno':eno_id}, dataType: 'json', success: function(data) { alert("成功"); }, error: function() { alert("保存失败"); } }); }); }) }) </script> 完全没有进入click的function里面,请问这是什么原因?以上的js代码有没有错误?
swjtutipo 2014-11-03
  • 打赏
  • 举报
回复
先将我的解决代码放在这里,以供后来者参考。 JS代码: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ type: 'POST', url: 'savedate/', data:{"ServiceNumber":$("#ServiceNumber").val(),"CustNumber":$("#OneCustNumber").val(),"Date":temp}, // contentType: "application/json",//该句代码不能加,加了之后无法POST dataType: 'json', success: function(data) { alert("成功"); }, error: function() { alert("保存失败"); } }); });
swjtutipo 2014-11-03
  • 打赏
  • 举报
回复
引用 3 楼 micropentium6 的回复:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax AJAX While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many javascript frameworks provide hooks that allow headers to be set on every request.
我在AJAX POST之前在Header里面加入了csrftoken,但是是单独放在一个JS文件里面,加载这个JS文件的时候出的问题。现在已经解决了,感谢的回答
swjtutipo 2014-11-03
  • 打赏
  • 举报
回复
引用 6 楼 devilzy2656 的回复:


def editShowingIndex(request,ID):
    objs = Show.objects.filter(id=ID)
    obj = {}
    signs = {}
    vals = ""
    for o in objs:
        obj = o
        signs = obj.sign.all()
    print signs
    for s in signs:
        vals+=s.name+","
    return ResponseUtils.csrfResponse(request,'pages/admin/show/show_shows_edit.html',{"obj":obj,"signs":vals})

#更新类别
def updateShow(request):
    ID = request.POST.get('id','')
    TITLE = request.POST.get('title','')
    CONTENT = request.POST.get('content','')
    STATE = request.POST.get('state','')
#     TIMES = request.POST.get('times','')
    IMAGE = request.POST.get('image','')
    URL = request.POST.get('url','')
#     NAMES = request.POST.get('signs','')
    c = Category.objects.get(name="推荐文章")
    
    shows = {}
    if ID!="":
        shows = Show.objects.filter(id=ID)
    length = shows.__len__()
    show = Show()
    if length != 0:
        show = shows[0]
    
    show.title=TITLE
    show.content=CONTENT
    show.category=c
    show.state=STATE
#     show.times=TIMES
    show.image=IMAGE
    show.url=URL
    show.save()
    
#     names = NAMES.split(",")
#     for n in names:
#         signs = Sign.objects.filter(name=n)
#         sign = Sign() 
#         if shows.__len__()==0:
#             sign.name = n
#             sign.save()
#         else:
#             sign = signs[0]
#         show.sign.add(sign)
    return ResponseUtils.csrfResponse(request,'pages/admin/show/show_shows.html',{})


#coding:utf-8
from django.shortcuts import render_to_response,RequestContext
from django.http.response import HttpResponse
import json

def csrfResponse(request,url,param):
    return render_to_response(url,param, context_instance=RequestContext(request))

def normalResponse(url,param):
    return render_to_response(url,param)

def ajaxJsonResponse(result):
    return HttpResponse(json.dumps(result), mimetype="application/json") 

<form id="validate" method="POST" action="/rsblc_admin/showing/updateShow">{%csrf_token %}
	                            <div class="data-fluid">
	                                <div class="row-form">
	                                    <div class="span2">标题:</div>
	                                    <div class="span10">
	                                        <input type="text" id="title" name="title" class="validate[required,maxSize[8]]" value="{{obj.title}}"/>
	                                        <input type="hidden" id="id"  name="id" value="{{obj.id}}"/>
	                                        <span class="bottom">Required, max size = 8</span>
	                                    </div>
	                                </div>
	                                <div class="row-form">
	                                    <div class="span2">背景图片:</div>
	                                    <div class="span10">
	                                        <input type="text" id="image" name="image" value="{{obj.image}}" class="validate[required,custom[url]]"/>
	                                        <span class="bottom">Required, url</span>
	                                    </div>
	                                </div>
	                                <div class="row-form">
	                                    <div class="span2">链接文章:</div>
	                                    <div class="span10">
	                                        <input type="text" id="url" name="url" value="{{obj.url}}" class="validate[required,custom[url]]"/>
	                                        <span class="bottom">Required, url</span>
	                                    </div>
	                                </div>
	                                <div class="toolbar bottom tar">
	                                    <div class="btn-group">
	                                        <button class="btn btn-info" type="button" onClick="history.go(-1);">返回</button>
	                                        <button class="btn" type="submit">提交</button>
	                                    </div>
	                                </div>
	                            </div>                
                            </form>
这是我的代码,希望对你有帮助,这里设置了csrf
感谢这么认真的解决我的问题,虽然已经解决了,但你的代码给我一种新的思路,谢谢
阳小良 2014-10-16
  • 打赏
  • 举报
回复


def editShowingIndex(request,ID):
    objs = Show.objects.filter(id=ID)
    obj = {}
    signs = {}
    vals = ""
    for o in objs:
        obj = o
        signs = obj.sign.all()
    print signs
    for s in signs:
        vals+=s.name+","
    return ResponseUtils.csrfResponse(request,'pages/admin/show/show_shows_edit.html',{"obj":obj,"signs":vals})

#更新类别
def updateShow(request):
    ID = request.POST.get('id','')
    TITLE = request.POST.get('title','')
    CONTENT = request.POST.get('content','')
    STATE = request.POST.get('state','')
#     TIMES = request.POST.get('times','')
    IMAGE = request.POST.get('image','')
    URL = request.POST.get('url','')
#     NAMES = request.POST.get('signs','')
    c = Category.objects.get(name="推荐文章")
    
    shows = {}
    if ID!="":
        shows = Show.objects.filter(id=ID)
    length = shows.__len__()
    show = Show()
    if length != 0:
        show = shows[0]
    
    show.title=TITLE
    show.content=CONTENT
    show.category=c
    show.state=STATE
#     show.times=TIMES
    show.image=IMAGE
    show.url=URL
    show.save()
    
#     names = NAMES.split(",")
#     for n in names:
#         signs = Sign.objects.filter(name=n)
#         sign = Sign() 
#         if shows.__len__()==0:
#             sign.name = n
#             sign.save()
#         else:
#             sign = signs[0]
#         show.sign.add(sign)
    return ResponseUtils.csrfResponse(request,'pages/admin/show/show_shows.html',{})


#coding:utf-8
from django.shortcuts import render_to_response,RequestContext
from django.http.response import HttpResponse
import json

def csrfResponse(request,url,param):
    return render_to_response(url,param, context_instance=RequestContext(request))

def normalResponse(url,param):
    return render_to_response(url,param)

def ajaxJsonResponse(result):
    return HttpResponse(json.dumps(result), mimetype="application/json") 

<form id="validate" method="POST" action="/rsblc_admin/showing/updateShow">{%csrf_token %}
	                            <div class="data-fluid">
	                                <div class="row-form">
	                                    <div class="span2">标题:</div>
	                                    <div class="span10">
	                                        <input type="text" id="title" name="title" class="validate[required,maxSize[8]]" value="{{obj.title}}"/>
	                                        <input type="hidden" id="id"  name="id" value="{{obj.id}}"/>
	                                        <span class="bottom">Required, max size = 8</span>
	                                    </div>
	                                </div>
	                                <div class="row-form">
	                                    <div class="span2">背景图片:</div>
	                                    <div class="span10">
	                                        <input type="text" id="image" name="image" value="{{obj.image}}" class="validate[required,custom[url]]"/>
	                                        <span class="bottom">Required, url</span>
	                                    </div>
	                                </div>
	                                <div class="row-form">
	                                    <div class="span2">链接文章:</div>
	                                    <div class="span10">
	                                        <input type="text" id="url" name="url" value="{{obj.url}}" class="validate[required,custom[url]]"/>
	                                        <span class="bottom">Required, url</span>
	                                    </div>
	                                </div>
	                                <div class="toolbar bottom tar">
	                                    <div class="btn-group">
	                                        <button class="btn btn-info" type="button" onClick="history.go(-1);">返回</button>
	                                        <button class="btn" type="submit">提交</button>
	                                    </div>
	                                </div>
	                            </div>                
                            </form>
这是我的代码,希望对你有帮助,这里设置了csrf
阳小良 2014-10-16
  • 打赏
  • 举报
回复
除了上面说的csrf,你可以直接在setting中屏蔽csrf的使用。但是不建议这么做
nieoding 2014-10-15
  • 打赏
  • 举报
回复
楼上正解,官方文档里面有范例,基本原理就是在post数据里面添加csrf信息
  • 打赏
  • 举报
回复
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax AJAX While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many javascript frameworks provide hooks that allow headers to be set on every request.
swjtutipo 2014-10-08
  • 打赏
  • 举报
回复
引用 1 楼 gaoming655 的回复:
django 官网提供一个AJAX 的JS 需要加载
已经加载了那个JS 没有用仍然被403
gaoming655 2014-09-26
  • 打赏
  • 举报
回复
django 官网提供一个AJAX 的JS 需要加载

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧