我正在尝试将jquery集成到使用Django框架制作的Web应用程序中。然而,我很难试图使一个简单的ajax调用工作。我的模板文件包含表单html和javascript来处理ajax调用看起来像:
<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>
应该处理ajax调用的我的views.py看起来像:
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)
我如何传递结果变量以及我的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); } } });
当我在浏览器中刷新模板html页面时,我在控制台中得到null,表明cookie未设置或未定义。我缺少什么?