JS: optimum option for adding AJAX points



  • There's a list of HTML elements with a common parent:

    <div>
        <div>...</div>
        <div>...</div>
        <div>...</div>
    </div>
    

    I get the following points with AJAX request; they come as text:

    <div>...</div><div>...</div><div>...</div>
    

    As the most appropriate (and why) to add them at the end of the current list:

    <div>
        <div>...</div>
        <div>...</div>
        <div>...</div>
        <div>...</div><!-- Новый пункт -->
        <div>...</div><!-- Новый пункт -->
        <div>...</div><!-- Новый пункт -->
    </div>
    

    1. Take innerHTML (i.e. already existing paragraphs), add the result of AJAX, and put it into the parent:

    parentOfItems.innerHTML = parentOfItems.innerHTML + responseText;
    

    The first option seems to have worked very well, but when it is still used in a certain project where a bunch of processors have been hanged by the parent of the list, there have been defects; therefore, I have begun to look for alternatives to the idea; that is, in fact, the issue has arisen.


    2. Create a tight one.span) a cliff, put it in her innerHTML result AJAX-request and add this wrap to the parent:

    var wrapper = document.createElement('span');
    

    wrapper.innerHTML = responseText;

    parentOfItems.appendChild( wrapper );

    So the result is:

    <div>
    <div>...</div>
    <div>...</div>
    <div>...</div>
    <span>
    <div>...</div><!-- Новый пункт -->
    <div>...</div><!-- Новый пункт -->
    <div>...</div><!-- Новый пункт -->
    </span>
    </div>

    3. Create Time Put it in her. innerHTML AJAX-Request and add children to the parent of the list points:

    var tmpWrapper = document.createElement('div');

    tmpWrapper.innerHTML = responseText;

    for ( var i = 0; i < tmpWrapper.children.length; i++ ) {

    parentOfItems.appendChild( tmpWrapper.children[i] );
    

    }


    4. Another option just came to the head: to use JSON; i.e. to convert the exhaust to JSON, and on the client to unpack it and simply move the points into the parent. But this option seems to me the most axious.



  • The function should be used. https://developer.mozilla.org/ru/docs/Web/API/Element/insertAdjacentHTML

    var responseText = '<div>NEW1</div><div>NEW2</div><div>NEW3</div>';
    

    document.getElementById('d').insertAdjacentHTML('beforeend',responseText);

    <div id="d">
    <div>...</div>
    <div>...</div>
    <div>...</div>
    </div>


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2