Ajax触发的请求不会更新Django View [英] Ajax Triggered request doesn't update Django View

查看:96
本文介绍了Ajax触发的请求不会更新Django View的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将这个问题分解为最简单的例子.当请求为ajax时,使用更新的上下文呈现页面不会产生预期的结果.

I tried to break this problem down into the simplest example. When the request is ajax, rendering the page with an updated context doesn't produce the expected result.

<html>
    <body>
        {% if templateVariable %}
            <h1>{{ templateVariable }}</h1>
        {% endif %}

        <button id="testBtn">TEST</button>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> 
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                $(function() {
                    $('#testBtn').click(function(event) {
                        $.ajax({
                            type: "POST",
                            url: "./",
                            data: {
                                'x' : 'x',
                                'csrfmiddlewaretoken' : '{{ csrf_token }}'
                            }
                        });
                    });
                });
            });

        </script>
    </body>
</html>

views.py

def index(request):
    context = {}
    if 'x' in request.POST:
        context['templateVariable'] = 'I was updated via ajax'
        print('ajax ran')
        return render(request, 'index.html', context)
    context['templateVariable'] = 'I was not updated via ajax'
    print('ajax was not run')
    return render(request, 'index.html', context)

  • 当我第一次加载页面时,会打印"ajax未运行",templateVariable为我未通过ajax更新",并且页面按预期方式在h1标签中呈现.

    • When I first load the page, 'ajax was not run' is printed, templateVariable is 'I was not updated via ajax', and the page renders with that in the h1 tag as expected.

      当我单击testBtn时,我希望ajax请求触发if语句,更新上下文,并在h1标签中显示我是由ajax更新"的页面.

      When I click the testBtn, I expect the ajax request to trigger the if statement, update the context, and render the page with 'I was updated by ajax' in the h1 tag.

      相反,打印页面时会打印'ajax ran',但templateVariable仍为'我没有被ajax更新'.最初加载页面时,"ajax尚未运行"仅打印一次.

      Instead, 'ajax ran' is printed but templateVariable remains 'I was not updated by ajax' when the page is rendered. 'ajax was not run' only is printed once when the page is loaded initially.

      为什么我没有得到预期的结果?

      Why would I not be getting the expected result?

      似乎每个人都同意您不能使用ajax请求返回渲染和更新上下文变量,但是我仍然遇到麻烦,因为我相信这是可能的.这是一些备用代码:

      It seems everyone agrees that you cannot return a render and update context variables with an ajax request but I'm still having trouble with this as I believe this is possible. Here's some alternate code:

      <html>
          <body>
              {% if templateVariable %}
                  <h1>{{ templateVariable }}</h1>
              {% endif %}
      
              <h1 id="placeHolder"></h1>
      
              <button id="testBtn">TEST</button>
      
              <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> 
              <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
              <script type="text/javascript">
      
                  $(document).ready(function() {
                      $(function() {
                          $('#testBtn').click(function(event) {
                              $.ajax({
                                  type: "POST",
                                  url: "./",
                                  data: {
                                      'x' : 'x',
                                      'csrfmiddlewaretoken' : '{{ csrf_token }}'
                                  },
                                  success: function (data) {
                                      $('#placeHolder').html(data);
                                  },
                                  dataType: 'html'
                              });
                          });
                      });
                  });
      
              </script>
          </body>
      </html>
      

      views2.py

      def index2(request):
          context = {}
          if 'x' in request.POST:
              context['templateVariable'] = 'I was updated via ajax'
              print('ajax ran')
              return render_to_response('notIndex.html', context)
          context['templateVariable'] = 'I was not updated via ajax'
          print('ajax was not run')
          return render(request, 'index.html', context)
      

      notIndex.html:

      {% if templateVariable %}
          {{ templateVariable }}
      {% endif %}
      

      • 在此示例中,页面最初在上下文中加载有templateVariable,因为我未通过Ajax更新".
      • 单击testBtn时,ajax请求将触发视图中的if块.这将使用更新后的上下文呈现notIndex.html.
      • ajax调用的成功函数将生成的html从notIndex.html设置为h1标签.
      • 那么,如果页面与ajax调用所来自的页面不同,为什么仅用ajax可以触发页面渲染?

        So why is it only possible to trigger a page render with ajax if the page is not the same one that the ajax call came from?

        推荐答案

        您无法从AJAX返回渲染或重定向,这就是它的工作原理

        You can't return renders or redirects from AJAX, that's how it works

        如果您要基于服务器上发生的事情来更新UI,例如说您有购物车,并且想要在不刷新页面的情况下实现添加到购物车",则添加到购物车"按钮必须请求您在urls.py&中提供的终结点如果添加了对象,则该URL必须返回true;否则,该URL必须返回false,但不会在UI上对其进行更新,因此您需要使用Javascript手动更改购物车商品计数.

        If you want to update your UI based on something that happens on the server say you have a cart and you'd like to implement 'add to cart' without refreshing the page, the 'add to cart' button must request an endpoint you provided in your urls.py & that url must return true if object is added, or false if it wasn't, but it won't update it on the UI, you need to manually change the cart items count with Javascript.

        如果您尝试将渲染重定向或返回到ajax,它将获得HTML或重定向/渲染,没有其他内容.

        If you try to redirect or return a render to ajax, it will get the HTML or the redirect/render, nothing else.

        如果您要重定向,则需要使用JS来实现,但没有Django的上下文变量.

        if you want to redirect, you'll want to do that with JS but with no context variables from django.

        请参阅此参考

        这篇关于Ajax触发的请求不会更新Django View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆