• 장고 ajax통신 코드

    2017. 11. 16. 14:56

    by. 위지원

    출처 http://greenyant.blogspot.kr/2014/07/django-jquery-ajax-simple.html


    weejw@weejwPC:~/queryTester/blog$ tree

    .

    ├── __init__.py

    ├── __pycache__

    │   ├── __init__.cpython-34.pyc

    │   ├── admin.cpython-34.pyc

    │   ├── models.cpython-34.pyc

    │   ├── urls.cpython-34.pyc

    │   └── views.cpython-34.pyc

    ├── admin.py

    ├── admin.py~

    ├── apps.py

    ├── migrations

    │   ├── 0001_initial.py

    │   ├── __init__.py

    │   └── __pycache__

    │       ├── 0001_initial.cpython-34.pyc

    │       └── __init__.cpython-34.pyc

    ├── models.py

    ├── models.py~

    ├── templates

    │   └── ajaxtest.html

    ├── tests.py

    ├── urls.py

    ├── urls.py~

    ├── views.py

    └── views.py~



    views.py


    from django.shortcuts import render

    from django.views.generic.edit import CreateView

    from django.contrib.auth.forms import UserCreationForm

    from django.http import HttpResponse



    def ajaxTest(request):

        if request.is_ajax():

            data = "You click " + request.GET['click'] + " button"

            import json

            return HttpResponse(json.dumps({'message':data}), 'application/json')

        return render(request, 'ajaxtest.html')


    urls.py


    from django.conf.urls import url

    from . import views


    urlpatterns = [

        url(r'', views.ajaxTest, name='post_list'),

    ]



    ajaxtest.html


    <script src="https://d10ajoocuyu32n.cloudfront.net/jquery-1.9.1.min.js"></script>

    <script type="text/javascript">

     $(document).on("click", "#id_a", function() {

      var c_data = {};

      c_data['click'] = 'a';

      $.ajax({

       url : ".",

       dataType:"json",

       data: c_data

      }).done(function(msg) {

       $("#text_area").append("done : "+msg['message']+"<_br />");

      });

     });

    </script>


    <button id="id_a">

     a

    </button>


    <div id="text_area">

     Text Area


    </div>



    실행화면


    profile
    위지원

    데이터 엔지니어로 근무 중에 있으며 데이터와 관련된 일을 모두 좋아합니다!. 특히 ETL 부분에 관심이 가장 크며 데이터를 빛이나게 가공하는 일을 좋아한답니다 ✨

    '2017년 > Python' 카테고리의 다른 글