首页 > 解决方案 > 从 JSON 响应追加到 JQuery

问题描述

我正在尝试从 HTML 块内的响应中添加数据

我做了什么

...
    success: function () {
                  console.log($("#re-side-cart-items"))
                  $.getJSON('/cart.js', function (cart) {
                    $.each(cart.items, function (index, element) {
                        if(element.id == rewards_variant_id){
                          console.log($("#re-sidecart-item-template").html());
                          $("#re-side-cart-items").append($("#re-sidecart-item-template").html())
                        }
                    })
                  });
                },
    ....

我的 HTML 块被分配给这个 var htmlwid = $("#re-sidecart-item-template").html();

<div id="re-sidecart-item-template" class="hide">
    "<div class=cart-product row id=" + element.id + ">"
        <div class="col-lg-3 col-md-3 col-sm-4 product-img">
            <div class="image">
                <div class="aspect-container">
                    <img src="element.img" alt="element.handle" loading="lazy" />
                </div>
            </div>
        </div>
        <div class="col-lg-8 col-md-8 col-sm-7 product-info">
            <div class="product-title">
                <a href="/pages/program" target="_blank">element.title element.price/mo.</b></a>
            </div>             
        </div>
    </div>
</div>

我想从响应中获取元素值,它基本上没有按应有的方式工作。

标签: javascriptjquery

解决方案


我能够修复它

    success: function () {
    if (window.location.pathname == '/cart'){
        window.location.href = "/cart";      
      }
      else{
        $.getJSON('/cart.js', function (cart) {
        $.each(cart.items, function (index, element) {
            if(element.id == rewards_variant_id){
              $("#re-side-cart-items").append($('<div>').attr('id', element.id).attr('class', 'cart-product row')
              .append($('<div>').attr('class', 'col-lg-3 col-md-3 col-sm-4 product-img')
              .append($('<div>').attr('class', 'image')
              .append($('<div>').attr('class', 'aspect-container')
              .append($('<img>').attr('src', element.image).attr('alt', element.product_title).attr('loading', 'lazy')))))
              .append($('<div>').attr('class', 'col-lg-8 col-md-8 col-sm-7 product-info')
              .append($('<div>').attr('class', 'product-title')
              .append($('<a>').attr('href', element.url)
              .append(element.product_title + ' ' + element.price/100 + '/mo.') 
              )
              .append($('<div>').attr('class', 'cart-pricing')
              .append($('<a>').attr('href', '/cart/change?line='+element.index+'&amp;quantity=0').attr('data-line', element.id)
              .append('<u>Remove</u>') 
              ))
              ))
              );
            }
        })
      });
      }
    },

推荐阅读