How do I integrate Ajax with Django applications?

前端 未结 8 505
忘了有多久
忘了有多久 2020-11-22 06:16

I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have

相关标签:
8条回答
  • 2020-11-22 06:45

    Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out: Bjax

    Usage:

    <script src="bjax.min.js" type="text/javascript"></script>
    <link href="bjax.min.css" rel="stylesheet" type="text/css" />
    

    Finally, include this in the HEAD of your html:

    $('a').bjax();
    

    For more settings, checkout demo here: Bjax Demo

    0 讨论(0)
  • 2020-11-22 06:49

    I am writing this because the accepted answer is pretty old, it needs a refresher.

    So this is how I would integrate Ajax with Django in 2019 :) And lets take a real example of when we would need Ajax :-

    Lets say I have a model with registered usernames and with the help of Ajax I wanna know if a given username exists.

    html:

    <p id="response_msg"></p> 
    <form id="username_exists_form" method='GET'>
          Name: <input type="username" name="username" />
          <button type='submit'> Check </button>           
    </form>   
    

    ajax:

    $('#username_exists_form').on('submit',function(e){
        e.preventDefault();
        var username = $(this).find('input').val();
        $.get('/exists/',
              {'username': username},   
              function(response){ $('#response_msg').text(response.msg); }
        );
    }); 
    

    urls.py:

    from django.contrib import admin
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('exists/', views.username_exists, name='exists'),
    ]
    

    views.py:

    def username_exists(request):
        data = {'msg':''}   
        if request.method == 'GET':
            username = request.GET.get('username').lower()
            exists = Usernames.objects.filter(name=username).exists()
            if exists:
                data['msg'] = username + ' already exists.'
            else:
                data['msg'] = username + ' does not exists.'
        return JsonResponse(data)
    

    Also render_to_response which is deprecated and has been replaced by render and from Django 1.7 onwards instead of HttpResponse we use JsonResponse for ajax response. Because it comes with a JSON encoder, so you don’t need to serialize the data before returning the response object but HttpResponse is not deprecated.

    0 讨论(0)
提交回复
热议问题