jQuery / JavaScript анализирует AJAX-ответ - PullRequest
0 голосов
/ 02 октября 2018

Я получаю ответ AJAX с сервера (сервер обработал обновление корзины покупок), который содержит различные элементы.Вот пример того, как это выглядит:

<div id="blockcart-wrapper">
<div class="shoppingcart-background" id="bg-div"></div>
    <div class="blockcart cart-preview" data-refresh-url="//localhost/backend/index.php?fc=module&amp;module=shoppingcart&amp;controller=ajax">
        <div class="header">
            <a rel="nofollow" href="#">
                <img class="cart-icon" src="someImage"
                     onclick="toggleClass()">
                            </a>
        </div>
        <div class="body" id="shopping-cart-body">
            <div class="close">
                <a href="#" onclick="toggleClass()">
                    <img class="icon" height="20px" width="20px" src="someImage">
                </a>
            </div>
            <h1 class="shopping-cart-header">Shoppingcart</h1>
            <div class="products-container">
                                    <div class="product">
                        <span class="product-image"><img src="someImage"></span>
                        <div class="product-details">
                            <h2 class="name-header">Name</h2>
                            <div class="product-quantity-details">
                                <span class="quantity">19</span>
                                                                    <a href="http://backend/increase" class="js-decrease-product-quantity" data-link-action="update-quantity">-</a>

                                                                    <a id="link1" href="https://backend/decrease" class="js-increase-product-quantity" data-link-action="update-quantity">+</a>

                                <span class="color-circle">
                                                                    </span>
                            </div>
                            <div class="price-open">
                                <span class="product-price">14,16 €</span>
                                <span class="product-link"><a href="http://localhost/backend/linkToProduct">öffnen</a></span>
                            </div>
                              <a
    class="remove-from-cart"
    data-link-action="remove-from-cart"
    data-id-product="6"
    data-id-product-attribute="0"
    href="http://backend/remove"
    rel="nofollow"
   >
    Remove
  </a>
                        </div>
                    </div>
                            </div>

            <div class="checkout">
                <div class="meta-data-wrap">
                                        <div class="cart-total label-row">
                        <span class="label">Total</span>
                        <span class="value">269,06 €</span>
                    </div>
                </div>

                                                                <a href="/index.php?controller=order" class="checkout-step">
                    <button type="button" class="dark">Checkout</button>
                </a>
            </div>
        </div>

Проблема в том, что респон содержит около 25000 LOC, которые в основном не имеют значения.Поэтому я хочу проанализировать эту часть ответа и вставить ее в фактический HTML.Что я сделал до сих пор:

document.getElementById('link1').addEventListener('click', function(ev){
    ev.preventDefault();
    console.log(ev);

        $.ajax({
        url: this.href,
        type: "GET",
        dataType: "html",
          success: function(data) {
              console.log($(data).text()); 
          }
    });
});

Это дает мне полный ответ.Итак, с этого момента я попытался найти div с идентификатором blockcart-wrapper, который является моей «точкой входа» для замены старого HTML, поэтому я сделал:

document.getElementById('link1').addEventListener('click', function(ev){
    ev.preventDefault();
    console.log(ev);

        $.ajax({
        url: this.href,
        type: "GET",
        dataType: "html",
          success: function(data) {
              console.log($(data).find('#blockcart-wrapper')); 
          }
    });
});

Но это дает мне jQueryобъект, а не содержимое HTML в этом div.
Может ли кто-нибудь помочь мне разобрать упомянутый div и заменить «старый» новым разобранным?

Ответы [ 2 ]

0 голосов
/ 02 октября 2018

Если вы не можете получить меньший ответ, попробуйте получить частичное:

Запишите пробел перед селектором

url: this.href + ' #blockcart-wrapper'

или

$("#container").load(location.href + ' #blockcart-wrapper')
0 голосов
/ 02 октября 2018

Но это дает мне объект jQuery, а не содержимое HTML в этом div.

Вы должны использовать .html() для возврата HTML-кода внутри div, например:

console.log( $(data).find('#blockcart-wrapper').html() );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...