【问题标题】:load part of the html page when filtering results with ajax使用ajax过滤结果时加载部分html页面
【发布时间】:2017-08-26 23:54:24
【问题描述】:

我想使用 3 个复选框过滤搜索结果。结果显示在 div 中,id=posts_results

   <div class="checkbox">
      <label><input type="checkbox" id="id1" class="typePost" value="En groupe"> val1 </label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id2" class="typePost" value="En groupe"> val2 </label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id3" class="typePost"  value="A domicile"> val3</label>
   </div>
   <div class="checkbox">
      <label><input type="checkbox" id="id4" class="typePost" value="Par webcam"> val4</label>
   </div>

  <div id="posts_results">

            {% include 'posts/posts_results.html' %}

   </div>


    <script>
        $('.typePost').change(function (request, response) {

        var v1=$('#id1').is(":checked")? 1:0;
        var V2=$('#id2').is(":checked")? 1:0;
        var V3=$('#id3').is(":checked")? 1:0;
        var v4=$('#id4').is(":checked")? 1:0;
        $.ajax({

            url: '/posts/type_lesson/',
            dataType: 'json',
            type: "GET",
            data: {
                group: groupChecked,
                webcam: webcamChecked,
                home: homeChecked,
                move: moveChecked,
                distance: distance,
            },
            success: function (object_list) {

                $('#posts_results').load("my_page.html", object_list);
                alert('after')
            }

        });

    });
   <script>

这是我的网址:

url(r'^filter/$', views.filter, name='filter_type_lesson'),

这是我的观点:

def filter(request):
if request.method=='GET':

    #as an exemple I'll send all posts
    data= PostFullSerializer(Post.objects.all(), many=True)
    return JsonResponse(data.data, safe=False)

过滤器函数根据json发送的数据执行一些过滤器,将过滤后的帖子序列化后发回(这里我以发送所有帖子为例)。

在 id 为“posts_results”的 div 中使用 forloop 显示结果,html 位于文件 posts_results.html 中。

发送了json数据但是ajax成功函数没有更新或加载div

也可以留下来

【问题讨论】:

  • this 不是load() 的第一个参数应该是的网址。
  • 我编辑它。我只是在测试它,但这不是问题

标签: javascript jquery html ajax django


【解决方案1】:

我喜欢尽可能远离原始 POST 数据,让表单 API 完成繁重的工作。您可以用更少的代码以更安全的方式完成现有工作。

创建一个包含四个 BooleanField 的表单,这些 BooleanField 以模型中的 BooleanField 命名。您可以使用 label 变量覆盖它们在 HTML 中的显示方式。

class TheForm(forms.Form):
    my_field = forms.BooleanField(required=False, label="What I want it to say")
    my_field2 = forms.BooleanField(required=False, label="What I want it to say 2", help_text="Something else")
    my_field3 = forms.BooleanField(required=False, label="What I want it to say 3", help_text="Something else")

输出为&lt;form class="my_form"&gt;{% csrf_token %}{{form.as_table}}&lt;/form&gt;

用JS这样提交:

$('.my_form input[type=checkbox]').change(function(e){
    e.preventDefault()
    $.post('module/filer/', $('.my_form').serialize(), function(data) {
        // Handle data
    });
});

提交并验证表单后,获取cleaned_data 属性并像这样过滤您的模型

models = Post.objets.filter(**form.cleaned_data)

这将起作用,因为表单字段和命名与模型中的字段相同。与Post.objects.filter(my_field=True, my_field2=True, my_field3=False) 相同。然后你可以用它做任何你想做的事情。我会使用FormView 来完成这一切:

class MyView(FormView):
    form_class = TheForm

    def form_valid(self, form):
        models = Post.objets.filter(**form.cleaned_data)
        data= PostFullSerializer(data, many=True)
        return JsonResponse(data.data, safe=False)

现在没有任何东西会自行更新 div。它仅在最初请求 HTML 时创建。在您的成功函数中,您需要像这样手动添加元素:

$('.my_form input[type=checkbox]').change(function(e){
    e.preventDefault()
    $.post('module/filer/', $('.my_form').serialize(), function(data) {
        var post_results = $('#post_results').html(''); // Clear out old html
        $.each(data, function(item) {
            // Create new divs from ajax data and append it to main div
            var div = $('<div>');
            div.append($('<div>').html(item.my_field));
            div.append($('<div>').html(item.my_field2).addClass('something'));
            div.appendTo(post_results);
        });
    });
});

你也可以直接通过 ajax 渲染 HTML 并执行$('#post_results').html(data);。您可以在 FormView 上调用 self.render_to_response,而不是调用 json 响应。

【讨论】:

  • 好的我知道了,但是什么是item(函数的参数),什么是item.some_field?
  • 应该是 my_field 和 my_field2。它是模型上调用的任何字段。我给出的只是一个例子。你只需要查看那个 json 响应,找到 ojbect 列表,然后循环遍历它们,然后在 HTML 中对它们做任何你想做的事情。
【解决方案2】:

也许您可以尝试在视图中渲染模板,然后将渲染的数据加载到您的 div 中。

假设您的posts/posts_results.html 是:

<ul>
{% for post in posts %}
    <li> Post: {{post.name }} / Author: {{post.author}} / Date: {{post.created_at}}</li>
{% endid %}
<ul>

在您看来,当您执行相应操作时,您可以渲染模板并将html内容添加到响应中,即(基于您当前的代码):

def filter(request):
    if request.method=='GET':
        json_data = {
            "success": False,
            "message": "Some message",
            "result": "some result",
        }
        posts = Post.object.all()
        template = "posts/posts_results.html"

        things_to_render_in_your_template = {
            "posts": posts, # you can add other objects that you need to render in your template
        }

        my_html = get_template(template)
        html_content = my_html.render(things_to_render_in_your_template)

        # here the html content rendered is added to your response
        json_data["html_content"] = html_content
        json_data["success"] = True
        return JsonResponse(json_data)

然后在你的 JS 中,在检查 ajsx 响应的时刻,你可以将渲染的内容添加到你的 div 中

$.ajax({

        url: '/posts/type_lesson/',
        dataType: 'json',
        type: "GET",
        data: {
            group: groupChecked,
            webcam: webcamChecked,
            home: homeChecked,
            move: moveChecked,
            distance: distance,
        },
        success: function (response) {
            # response is the json returned from the view, each key defined in your json_data dict in the view, is a key here too 

            # now insert the rendered content in the div
            $('#posts_results').html(response["html_content"]);
            alert('after');
        }

    });

我建议你不要为你的ajax请求创建一个一个数据,使用jquery的serialize方法或者创建一个FormData对象,也可以代替GET,使用POST来做你的请求更安全

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 2010-09-08
    • 2014-12-04
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多