简体   繁体   中英

Pass ajax response to django template

I am learning to use javascript, ajax, python and django together.

In my project, a user selects a language from a drop-down list. Then the selected is sent back to the server. Then the server sends the response back to the django template. This is done by javascript. In the django template, I need the response, for example, German, to update the html code. How to pass the response to the html code. The response can be seen in the range of ....

How to do it without reload the html page?

Thanks.

You could use jquery to send the ajax request and server could send the response with html content. For example,

Server: When server receives the ajax request. This would return the html content ie a template which could be rendered to the client via ajax

def update_html_on_client(request):
    language = request.GET.get('language', None)
    #for selected language do something
    cal_1 = ...
    return render_to_response('my_template.html', {'cal':cal_1}, content_instance = template.RequestContent(request))

Template: This is example of ajax function you would use to generate ajax request. You can select the div in which you can populate the html response returned by the server.

function getServerResponse(){
$.ajax({
  url: 'your_url_here',
  data: {language:'German'},
  dataType:'html'
  success : function(data, status, xhr){
               $('#server_response').html(data);
             }
});
}

Because your templates are rendered on the server, your best bet is to simply reload the page (which re-renders the page with your newly selected language).

An alternative to using ajax would be to store the language in a cookie, that way you don't have to maintain state on the client. Either way, the reload is still necessary.

You could investigate client side templating. Handlebars is a good choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM