Returning HTML With fetch()

后端 未结 5 1834
暗喜
暗喜 2020-11-28 03:45

I\'m trying to fetch a file and return it\'s HTML. However it\'s not as simple as I\'d have imagined.

    fetch(\'/path/to/file\')
    .then(function (respon         


        
相关标签:
5条回答
  • 2020-11-28 04:06

    You need to use the .text() method, instead of .json(). This converts the byte stream into plain text, which can be parsed by the browser as HTML.

    0 讨论(0)
  • 2020-11-28 04:09
    • 1- call function fetch and add the path of the page.
    • 2- then convert the fetch data to text by function .text().
    • 3- then append the page component to your parent container.

           async function getAbout() {
    
    
        await fetch('./component/about.html').then(res => res.text()).then(data => {
        page_2.innerHTML = data;
    
         }).then(() => {
           
             // after fetch write js code here  
         })}

    • for fetch, component don't add <body> or <HTML> tag < just use other like <div> or other tags.

    • for better performance use async-await!.

    0 讨论(0)
  • 2020-11-28 04:12

    you can return the response with .text(), and then render the page in the doc as you want.

    function fetchHtml() {
      fetch('./file.html')
      .then((response) => {
        return response.text();
      })
      .then((html) => {
        document.body.innerHTML = html     
      });
    }
    
    0 讨论(0)
  • 2020-11-28 04:22

    You can download the html with fetch and then parse it with DomParser API.

    fetch('somePage.html')
        .then(function(response) {
            // When the page is loaded convert it to text
            return response.text()
        })
        .then(function(html) {
            // Initialize the DOM parser
            var parser = new DOMParser();
    
            // Parse the text
            var doc = parser.parseFromString(html, "text/html");
    
            // You can now even select part of that html as you would in the regular DOM 
            // Example:
            // var docArticle = doc.querySelector('article').innerHTML;
    
            console.log(doc);
        })
        .catch(function(err) {  
            console.log('Failed to fetch page: ', err);  
        });

    0 讨论(0)
  • 2020-11-28 04:23

    It should be:

    fetch('/path/to/file').then(function(response) {
        return response.text();
    }).then(function(string) {
        console.log(string);
    }).catch(function(err) {  
        console.log('Fetch Error', err);  
    });
    
    0 讨论(0)
提交回复
热议问题