【问题标题】:Failing to display json into html with ajax无法使用 ajax 将 json 显示为 html
【发布时间】:2021-05-03 19:54:08
【问题描述】:

我正在为我的帖子实现一个“加载更多”按钮。

使用 ajax 这就是我将加载的帖子显示到我的 html 中的方法:

success:function(res){
                var _html='';
                var json_data=$.parseJSON(res.posts);
                $.each(json_data,function(index,data){
                _html+='<div class="post-box col-md-1">\
                  <div class="info-box mb-4">\
                  <div>\
                    {% if '+data.fields.cantidad+' == 1 %}\
                      <h3>'+data.fields.donador+'</h3><text>te donó '+data.fields.cantidad+' '+data.fields.objeto+'.</text>\
                    {% else %}\
                    <h3>'+data.fields.donador+' </h3><text>te donó '+data.fields.cantidad+' '+data.fields.objeto+'s.</text>\
                    {% endif %}\
                      <br>\
                      <text>'+data.fields.whenpublished+' </text>\
                      {% if '+data.fields.message+' != "" %}\
                      <hr>\
                    <text>'+data.fields.message+'</text>\
                    {% endif %}\
                  </div>\
                  </div>\
              </div>';
                              };

这是我的模型:

class Donacion(models.Model):
    creador_d = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    creation_date = models.DateTimeField(auto_now_add=True, blank=True)
    message = models.CharField(max_length=300, null=True, blank=True)
    donador = models.CharField(max_length=30, null=True, blank=True)
    cantidad = models.IntegerField()
    objeto = models.CharField(max_length=30, null=True, blank=True)

    def whenpublished(self):
        now = timezone.now()
        
        diff = now - self.creation_date

        if diff.days == 0 and diff.seconds >= 0 and diff.seconds < 60:
            seconds= diff.seconds
            
            if seconds == 1:
                return "Hace " + str(seconds) +  " segundo"
            
            else:
                return "Hace " + str(seconds) +  " segundos"

            

        if diff.days == 0 and diff.seconds >= 60 and diff.seconds < 3600:
            minutes= math.floor(diff.seconds/60)

            if minutes == 1:
                return "Hace " + str(minutes) +  " segundo"
            
            else:
                return "Hace " + str(minutes) +  " minutos"



        if diff.days == 0 and diff.seconds >= 3600 and diff.seconds < 86400:
            hours= math.floor(diff.seconds/3600)

            if hours == 1:
                return "Hace " + str(hours) +  " hora"

            else:
                return "Hace " + str(hours) +  " horas"

      

这里有一些问题。

  1. '+data.fields.whenpublished+':这个值返回undefined,不知道怎么访问
  2. 这个条件:{% if '+data.fields.cantidad+' == 1 %}被解释为False,而'+data.fields.cantidad+'实际上是一个1
  3. 这个条件:{% if donacion.message != '' %} 它被解释为 True 即使 '+data.fields.message+' == '' 在这种情况下它应该被解释为 False

为了让您比较这个 ajax html,我会为您提供我通常用来通过 GET 方法呈现我的帖子的那个:

     <div class="post-box col-md-1">
          <div>
              <div>
                    {% if donacion.cantidad == 1 %}
                      <h3>{{donacion.donador}} </h3><text>te donó {{donacion.cantidad}} {{donacion.objeto}}.</text>
                    {% else %}
                    <h3>{{donacion.donador}} </h3><text>te donó {{donacion.cantidad}} {{donacion.objeto}}s.</text>
                    {% endif %}
                      <br>
                      <text>{{ donacion.whenpublished }}</text>
                      {% if donacion.message != '' %}
                      <hr>
                    <text>{{donacion.message}}</text>
                    {% endif %}
              </div>
          </div>
      </div>

views.py

def load_more(request):
    offset=int(request.POST['offset'])
    limit=2
    posts=Post.objects.all()[offset:limit+offset]
    totalData=Post.objects.count()
    data={}
    posts_json=serializers.serialize('json',posts)
    return JsonResponse(data={
        'posts':posts_json,
        'totalResult':totalData
    })

【问题讨论】:

  • 也分享你的views.py。服务端是如何处理的?
  • 完成@NKSM 它是共享的

标签: python html django ajax


【解决方案1】:

您的whenpublished 是您的模型的方法。

实际上你不需要使用serializer

尝试这样做:

def load_more(request):
    offset = int(request.POST['offset'])
    limit = 2
    posts = Post.objects.all()[offset:limit+offset]
    totalData = Post.objects.count()
    posts_data = [{
        'cantidad': post.cantidad,
        'donador': post.donador,
        'whenpublished': post.whenpublished(),
        "message": post.message } for post in posts]
    return JsonResponse(data={
        'posts':posts_data,
        'totalResult':totalData
    })

然后在您的 AJAX 成功中,您可以使用 res.posts 而不是 var json_data = $.parseJSON(res.posts);

【讨论】:

  • @NicolasAgustin,在这种情况下使用迭代更容易,因为您需要调用模型方法。当您只需要模型字段时,您也可以使用values 作为示例queryset.values("message","donador", ...)
  • 我设法通过views.py 上的 if 条件解决了第 2 点,并从 html 中删除了 if 逻辑,但我该如何解决第 3 点?我必须删除 &lt;hr&gt;如果消息为空
  • @NicolasAgustin,但你为什么要在你的 javascript 中使用 django 模板标签?
  • 我认为它可以工作,但事实证明它没有。正如您在我的代码中看到的那样,我使用 django 模板标签通过 get 方法管理一些逻辑。但是我无法从“加载更多”操作中替换该 django 逻辑。
    如果消息为空且不知道如何删除,我必须删除它。
  • @NicolasAgustin,你必须使用 JavaScript if else.
【解决方案2】:

Django 将加载模板并根据请求提供它,在页面提供后注入新代码不会做任何事情。

通常在后端做一个单独的API端点,前端调用它并异步加载数据

在您的情况下,您可以使用 js 来加载数据并注入 HTML 元素而不是“代码”

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2017-09-14
    • 2010-10-27
    相关资源
    最近更新 更多