【问题标题】:How to use Ajax in Django-templates?如何在 Django 模板中使用 Ajax?
【发布时间】:2014-02-17 21:39:40
【问题描述】:

如何在 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>

我如何在您按下 OK 按钮时做到这一点仅更新页面的一部分在标签 h1 之间?

【问题讨论】:

标签: python html ajax django django-templates


【解决方案1】:

这就是我在 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>

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2012-06-10
    • 2015-09-07
    • 2021-12-11
    • 2018-08-28
    • 2017-11-16
    • 2012-08-09
    • 2015-12-23
    • 2015-03-06
    相关资源
    最近更新 更多