【问题标题】:Best way to return data In JSON在 JSON 中返回数据的最佳方式
【发布时间】:2016-11-11 05:25:43
【问题描述】:

大家好,我使用 ajax 在我的网站中修改了一个 div

我有这个完美的函数,但是我在获取返回的值时遇到了问题

updatecart = function(qty, id_product) {
    var currentVal, data, id, item_hash, request;
    currentVal = void 0;
    id = void 0;
    data = void 0;
    item_hash = void 0;
    currentVal = parseFloat(qty);
    id = parseInt(id_product);
    request = $.ajax({
      url: ajax_object.ajax_url,
      method: 'POST',
      data: {
        quantity: currentVal,
        id_product: id,
        action: 'update_my_cart',
        dataType: "json"
      },
      success: function(html, data) {
        var array_fields, fields, pos, total_amount;
        pos = html.indexOf("[");
        fields = html.slice(pos + 1, -1);
        array_fields = fields.split(',');
        id = parseInt(array_fields[0].replace(/\"/g, ""));
        total_amount = (array_fields[1] + ',' + array_fields[2]).replace(/[\\"]/g, '');
        $('.total' + id + ' .woocommerce-Price-amount').replaceWith($(total_amount));
        $('.amount_cart .amount').replaceWith('.amount', html);
        console.log('update cart');
      },
      error: function(errorThrown) {
        console.log(errorThrown);
      }
    });   };

在这种情况下返回 html 和数据。

数据 = “成功”

而html是

<div class="total_purchase">
  <div class="col-xs-12">
    <div class="subtotal_cart">
      <span class="item_purchase">
        Sub-total:      </span>
      <span class="amount_cart">
        <span class="woocommerce-Price-amount amount">15,40&nbsp;<span class="woocommerce-Price-currencySymbol">&euro;</span></span>      </span>
    </div>
  </div>

<div class="col-xs-12">
  <div class="wc-proceed-to-checkout">

<a href="http:../checkout/" class="checkout-button button alt wc-forward">
    Checkout</a>
  </div>
</div>

</div>

我必须剪切并使用字符串来获取我的日期,并在最后替换 div。

即使在最后一行我也无法替换数据

$('.amount_cart .amount').replaceWith('.amount', html);

什么是最好的方式或以其他方式返回日期以获得我需要的信息。

感谢您的建议!

【问题讨论】:

  • 您没有显示您的update_my_cart() ajax 回调。虽然约翰的回答是您需要添加到该回调的内容。

标签: jquery html json woocommerce


【解决方案1】:

服务器端你必须用 json_encode() 返回日期

json_encode(array( 'mydate' => $my_date ));

如果你想在你的 HTML 中显示日期,你必须在你的 ajax 成功中这样做。

success: function(json) {
    $('.amount_cart .amount').html(json.mydate);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2020-09-03
    • 2015-06-19
    • 2018-04-22
    • 2017-05-18
    相关资源
    最近更新 更多