简体   繁体   English

如何在Django模板中使用Ajax?

[英]How to use Ajax in Django-templates?

How to use Ajax in Django-templates? 如何在Django模板中使用Ajax?

urls.py urls.py

from django.conf.urls import patterns, url

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

views.py 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 的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>

How can I do that when you press the OK button updates only part of the page between the tags h1 ? 当您按“确定”按钮时, 如何 仅更新标签h1之间的部分页面

This is how I handle it in Flask, but since you are working with Django it will be easy to fit the code. 这就是我在Flask中处理它的方式,但是由于您正在使用Django,因此很容易编写代码。

Server: import jsonify 服务器:导入jsonify

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

Client-side: 客户端:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM