2017년/Python

장고 ajax통신 코드

위지원 2017. 11. 16. 14:56

출처 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>



실행화면