• 장고 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>



    실행화면


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

    장고 time.now()를 쓰면 디비에 이상한 시간이 들어간다  (3) 2017.11.22
    redis  (0) 2017.11.22
    장고 에러로그 파일로 남기기  (0) 2017.11.16
    장고 view,url  (0) 2017.11.15
    python anywhere 사용하기  (0) 2017.11.15

    대화의 장 💬