首页 > 解决方案 > 尝试在 AJAX 调用后将一个 html 页面注入另一个页面但返回空白

问题描述

我正在尝试将一个带有 django 函数的 html 模板注入到另一个 html 模板中。该函数依赖于对其变量的 AJAX 调用。

我的 AJAX 调用似乎正确触发(在检查 Chrome 开发工具后),但结果未按应有的方式显示在 html 页面上。

这是 AJAX 调用

//dashboard
$(document).ready(function(){
    console.log('Document Ready')
    $.ajax({
            type: "GET",
             url : '/electra/playlist',
             dataType: "json",
             data: {
                 'venue': 'venue',
                 'list':  'list',
                },
                    success: function(data){
                    $("#playlist").html(data);
                    console.log(data)
                    },
                    failure: function(errMsg) {
                        alert(errMsg);
                    }
                    });
    });

这是Django函数发生的html文件playlist.html

<!--what is the purpose of this fragmented code?-->
<div class="user_playlists">
  <ul>
    {% for item in playlist %}
      <li>
        <div>
            <h6 class="playlist-name">{{ item.list }}</h6>
            <h6 class="venue-name">{{ item.venue }}</h6>
        </div>
      </li>
    {% endfor %}
  </ul>
</div>

这是dashboard.html模板中playlist.html应该注入函数的部分:

<body>
    {% block content %}
        <div class="container-fluid" style="padding:15px">
          <!--location -->
          <div class="row">
            <div class="col-sm-3">
              <h3 class="list-heading"> Your Playlists </h3>
              <div id="playlist">
              </div>
            </div>
          </div>
        </div>
    {% endblock %}

请注意,我已经尝试过{% include "playlist.html" %}并且希望尽可能避免这种情况,我还有另外两个 html 模板以类似的方式工作,但没有 django 功能。

如果它也有帮助,这里是views.py:

@ensure_csrf_cookie
def dashboard(request):
    return render(request, 'testingland/dashboard.html')

class user_playlist(ListView):
    template_name = 'testingland/playlist.html'
    context_object_name = 'playlist'
    model = UserVenue

    def get_queryset(self):
        venue = self.request.GET.get('venue', None)
        list = self.request.GET.get('list', None)

        return UserVenue.objects.filter(list__user=self.request.user)

标签: htmldjangoajax

解决方案


您不需要发送json类型的数据。因此,只需删除该行应该可以正常工作:

    $.ajax({
            type: "GET",
            url : '/electra/playlist',
            // dataType: "json", ---> Remove this line
            data: {
                'venue': 'venue',
                'list':  'list',
            },
            success: function(data){
                $("#playlist").html(data);
                console.log(data)
            },
            failure: function(errMsg) {
                alert(errMsg);
            }
        });
    });

注意:- “弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调从 jQuery 3.0 开始被删除。您可以使用 jqXHR.done()、jqXHR.fail() 和jqXHR.always() 代替。” - jQuery


推荐阅读