블로그 이미지
흰색앵초

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

2012. 12. 13. 17:54 프로그래밍/장고

장고로 이런저런 기능을 구현하다보면 Ajax를 통한 비동기 방식이 필요할 때가 있다. 

간단한 예제를 통하여 방법을 알아보자.


먼저 views.py에 아래와 같이 추가한다.

    
def test(request):
    value = RequestContext(request, {'user':request.user})
    template = get_template('test.html')
    output = template.render(value)
    return HttpResponse(output)

def test2(request):
    name = request.GET['name']
    age = request.GET['age']
    value = RequestContext(request, {'name':name, 'age':age})
    template = get_template('test2.html')
    output = template.render(value)
    return HttpResponse(output)

특별한건 없고 예제 구현에 필요한 test.html, test2.html을 보여주는게 거의 대부분인 소스이다. Ajax를 통해 값을 넘길 때 GET 방식을 사용함으로 test2.html에는 request.GET을 사용하여 처리하였다.

test.html

아래는 템플릿 소스이다.

<p><br /></p>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
  $('#btn').click(function(){
   $.ajax({
   	url : '/test2/',
   	data : {name:'name1', age:'27'},
   	success:function(data){
   		$('body').append(data)
   	}
   });
  });
 });
</script>
 <input type="button" value="클릭" id="btn">
 <body>
</html>

test2.html
이름 : {{name}}
나이 : {{age}}

결과는 이름:21 나이:27로 출력된다.

posted by 흰색앵초