简体   繁体   中英

django ajax return template as data

How do you when making an ajax request to a view return the template data to the jquery call.

As an example, i am making an ajax call this way.

<script>
  function getProfile(username) {
     $.getJSON("/profiles/"+username, { username:{{ username }}}, function(json){
                            alert("Was successful?: " + json['success']);
                        });
                    }
   function addClickHandlers() {
           $(".person-name").click( function()
                getProfile(result.user.username) });
                    }
                    $(document).ready(addClickHandlers);
  </script>

My django view

def profiles_view(request, username):
#    if username:
#        selected_user = User.objects.get(username = username)
    results = {'success':False}
    if request.method == u'GET':
        GET = request.GET
        if GET.has_key(u'username'):
            results = {'success':True}
    json = simplejson.dumps(results)

    return HttpResponse(json, mimetype='application/json')

Can i pass my template view profiles_view.html to the HttpResponse? i am not sure where my template comes in?

If you need both HTML view and JSON view, you may need two responses. First is from TemplateResponse , second one is from HttpResponse . Two requests seem inefficient, but the first request is once for all, afterwards you only need JSON response by use of AJAX request.

You can return a template by:

 return TemplateResponse(request, "profiles_view.html", results)

如果您只是要通过ajax传递数据,则不需要模板。

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