2014-01-27 2 views
1

Django-templates에서 Ajax를 사용하는 방법은 무엇입니까?Django-templates에서 Ajax를 사용하는 방법?

urls.py

from django.conf.urls import patterns, url 

urlpatterns = patterns('', 
    url(r'^home/$', 'views.index'),) 

views.py

from django.template import RequestContext 
from django.shortcuts import render_to_response 

def index(request): 

    val = request.POST.get('val', default='text_text') 
    return render_to_response(
      'index.html', 
          {'text': val,}, 
          context_instance=RequestContext(request)) 

index.html을

<p>text and pictures</p> 
<p>text and pictures</p> 

<h1>{{ text }}</h1> 

<form action="/home/" method="post"> 
{% csrf_token %} 
<input type="text" name="val" id="val" value="{{ val }}"/> <br/> 
<input type="submit" value="OK" /> 
</form> 

<p>text and pictures</p> 
<p>text and pictures</p> 

어떻게하면이 OK 버튼을 누를 때 그렇게 할 수 있습니까? 은 태그 h1 사이에 페이지의 일부만 업데이트합니다.

+1

[? 장고에 가장 AJAX 라이브러리 란 (http://stackoverflow.com/ 질문/511843/what-is-the-the-best-ajax-django 라이브러리) –

+1

간단한 아약스 호출에 대한이 링크를 읽을 수 있습니다 http://stackoverflow.com/questions/21259988/dj ango-ajax-httpresponse-json-error-unexpected-token-d/21260734 # 21260734 –

답변

2

이것은 Flask에서 처리하는 방법이지만 장고로 작업하기 때문에 코드에 맞추기가 쉽습니다.

가 서버 : 가져 오기가

@app.route("/_jquerylink") 
def jquerylink(): 
    val = request.POST.get('val', default='text_text') 
    return jsonify(text=val) 

클라이언트 측 jsonify :

<div id="partwithh1"><h1>{{ text }}</h1></div> 

<form action="/home/" method="post"> 
    {% csrf_token %} 
    <input type="text" name="val" id="val" value="{{ val }}"/> <br/> 
    <input type="submit" onclick="getviews(this)" value="OK" /> 
</form> 

    <script type="text/javascript"> 

     $(function getviews() { 

      var content = $(#val).text(); 
      $SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; 
      $.getJSON($SCRIPT_ROOT + '/_jquerylink', 
        {'val':content} 
       , 
       function(data) { 
        $("#partwithh1").html(data.text); 
       }); 
      return false; 
      }); 

    </script> 
+0

고마워, 내가 시도해! – Olga

관련 문제