Sto cercando di integrare jquery in un’applicazione web che sto creando con il framework Django. Sto comunque avendo difficoltà a cercare di fare una semplice chiamata ajax
per funzionare. Il mio file modello che contiene il modulo html e javascript per gestire la chiamata ajax ha il seguente aspetto:
$(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; }); })
Il mio views.py
che dovrebbe gestire la chiamata ajax ha il seguente aspetto:
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!')
Ho cercato di seguire la documentazione ufficiale sulla protezione contraffatta della richiesta tra siti e ho anche esaminato diverse domande StackOverflow che affrontano un problema simile. Ho incluso il {% csrf_token %}
nel mio file modello html
ma sembra che non funzioni. Viene visualizzato un errore nella console che indica che la chiamata ajax non è riuscita:
POST http://127.0.0.1:8000/hello/ 403 (FORBIDDEN)
Come posso passare la variabile result
insieme alla mia risposta http e far funzionare correttamente la chiamata ajax? Qualsiasi aiuto è profondamente apprezzato.
Edit-1
Non avrei dovuto passare il token csrf
insieme alla mia richiesta di post. COSÌ come da documentazione ho aggiunto il seguente codice al mio template 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); } } });
Quando aggiorno la pagina HTML template nel browser, ottengo null
nella console, suggerendo che il cookie non è impostato o non definito. Cosa mi manca?