大佬教程收集整理的这篇文章主要介绍了jquery – 403在Django框架中制作ajax Post请求时被禁止的错误,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
<script type="text/javascript"> $(document).ready(function() { $( "#target" ).submit(function() { console.log('Form was submitted'); $.ajax({ type: "POST",url: "/Hello/",// or just url: "/my-url/path/" data: { query: $( "#query" ).val() },success: function(data) { console.log(data); } }); return false; }); }) </script> <form id="target" action="." method="post">{% csrf_token %} <input id= "query" type="text" value="Hello there"> <input type="submit" value="Search Recent Tweets"> </form>
from django.core.context_processors import csrf from django.shortcuts import render_to_response from django.template.loader import get_template from django.template import Context,requestContext from django.views.decorators.csrf import ensure_csrf_cookie from django.http import httpResponse # access resource def Hello(request): c = {} c.update(csrf(request)) if request.is_ajax(): t = get_template('template.html') #html = t.render(Context({'result': 'Hello world'})) con = requestContext(request,{'result': 'Hello world'}) return render_to_response('template.html',c,con) else: return httpResponse('Not working!')
我试图遵循Cross-Site Request Forgery Protection的官方文档,并且还查看了几个解决类似问题的stackoverflow问题。我已经在我的html模板文件中添加了{%csrf_token%},但它似乎还没有起作用。我在控制台中收到错误提示ajax调用失败:
POST http://127.0.0.1:8000/Hello/ 403 (FORBIDDEN)
@R_696_11399@传递结果变量以及我的http响应,并获得ajax调用工作顺利?任何帮助深深的赞赏。
编辑1
我不应该像我的帖子请求一样传递csrf令牌。根据文档我添加了以下代码到我的模板javascript:
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'); console.log(csrftoken); //Ajax call function csrfSafeMethod(method) { // these http methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ crossDomain: false,// obviates need for sameOrigin test beforeSend: function(xhr,setTings) { if (!csrfSafeMethod(setTings.typE)) { xhr.setrequestHeader("X-CSRFToken",csrftoken); } } });
以上是大佬教程为你收集整理的jquery – 403在Django框架中制作ajax Post请求时被禁止的错误全部内容,希望文章能够帮你解决jquery – 403在Django框架中制作ajax Post请求时被禁止的错误所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。