简体   繁体   中英

Load the part of a page in Ajax, not the entire page

I know how to load an entire page in Ajax, especially by getting the href to have something dynamic, but I would like to get a particular part of the loaded page.

I'm trying to create a modal window. In jQuery, I did it like this:

    (function($)
    {
        $(".trigger").on("click", function(e)
        {
            var url = $(this).attr('href') + " #container #content"
            e.preventDefault()
            $(".modal, #overlay").toggleClass("show")
            $(".modal .container").load(url, function()
            {
                $("#form").submit(function(event)
                {
                    event.preventDefault();
                })
            })
        })
        $("#overlay").on("click", function()
        {
            $(".modal, #overlay").removeClass("show")
        })
    })(jQuery)

Pure JavaScript:

    // Modal
    var modal = document.querySelector(".modal")
    var overlay = document.getElementById("overlay")

    // Open Modal
    var openModal = function(event)
    {
        event.preventDefault()
        modal.classList.toggle("show")
        overlay.addEventListener("click", closeModal)

        // Ajax
        var httpRequest = new XMLHttpRequest()

        httpRequest.onreadystatechange = function()
        {
            if(httpRequest.readyState === 4)
            {
                document.querySelector(".modal .content").innerHTML = httpRequest.responseText
            }
        }
        httpRequest.open("GET", this.getAttribute("href"), true)
        httpRequest.send()
    }

    // Close Modal
    var closeModal = function(event)
    {
        event.preventDefault()
        modal.classList.remove("show")
        overlay.removeEventListener("click", closeModal)
    }

    // Trigger
    document.querySelectorAll(".trigger").forEach(a => {
        a.addEventListener("click", openModal)
    })

In this part:

    httpRequest.open("GET", this.getAttribute("href"), true)

I would like to reproduce this in pure JavaScript:

    var url = $(this).attr('href') + " #container #content"

I would use fetch() and DomParser API's

var openModal = function(event) {
  event.preventDefault()
  ...


  const url = event.currentTarget.href;

  fetch(url)
    .then(res => res.text())
    .then(html => {
      const doc = new DOMParser().parseFromString(html, 'text/html');
      const content = doc.querySelector('#content').outerHTML;
      document.querySelector(".modal .content").innerHTML = content;

    });

}

Plunker demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM