2010-11-08 12 views
33

Ho scritto una vista che risponde a richieste Ajax dal browser. È scritto così -Come inviare una risposta vuota in Django senza modelli

@login_required 
def no_response(request): 
    params = request.has_key("params") 
    if params: 
     # do processing 
     var = RequestContext(request, {vars}) 
     return render_to_response('some_template.html', var) 
    else: #some error 
     # I want to send an empty string so that the 
     # client-side javascript can display some error string. 
     return render_to_response("") #this throws an error without a template. 

Come faccio?

Ecco come gestire la risposta del server sul lato client -

$.ajax 
    ({ 
     type  : "GET", 
     url  : url_sr, 
     dataType : "html", 
     cache : false, 
     success : function(response) 
     { 
      if(response) 
       $("#resp").html(response); 
      else 
       $("#resp").html("<div id='no'>No data</div>"); 
     } 
    }); 

risposta

58

render_to_response è una scorciatoia specificamente per il rendering di un modello. Se non si vuole fare questo, basta restituire un vuoto HttpResponse:

from django.http import HttpResponse 
return HttpResponse('') 

Tuttavia, in questa circostanza io non lo farei - si sta segnalando alla AJAX che c'è stato un errore, in modo da dovrebbe restituire una risposta di errore, possibilmente codice 400 - che puoi fare usando invece HttpResponseBadRequest.

+0

oh cool! semplice, quindi il mio problema si è rivelato piuttosto elementare! comunque grazie per l'aiuto. ho imparato qualcosa di nuovo oggi. –

9

Penso che il codice migliore per restituire una risposta vuota sia 204 No Content.

from django.http import HttpResponse 
return HttpResponse(status=204) 

Tuttavia, nel tuo caso, non si dovrebbe restituire una risposta vuota, dal momento che 204 mezzi: The server *successfully* processed the request and is not returning any content..

È meglio restituire un po 'di codice di stato 4xx per segnalare meglio che l'errore è in the client side. Yo può mettere qualsiasi stringa nel corpo della risposta 4xx, ma consiglio vivamente di inviare un JSONResponse:

from django.http import JsonResponse 
return JsonResponse({'error':'something bad'},status=400) 
Problemi correlati