2014-01-27 100 views
1

如何在Django模板中使用Ajax?如何在Django模板中使用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> 

我怎麼能這樣做,當你按下確定按鈕只更新標籤h1之間的頁面的一部分?

+1

[?什麼是最好的AJAX庫的Django(http://stackoverflow.com/問題/ 511843/what-is-the-best-ajax-library-for-django) –

+1

你可以閱讀這個鏈接爲簡單的ajax調用 http://stackoverflow.com/questions/21259988/dj ango-ajax-httpresponse-json-error-unexpected-token-d/21260734#21260734 –

回答

2

這就是我如何在Flask中處理它,但由於您正在使用Django,因此將很容易適合代碼。

服務器: 進口jsonify

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

客戶端:

<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

相關問題