Home > Software design >  How to select and load the content of external page
How to select and load the content of external page

Time:10-09

In the example below I have a selection box that for each selection made, a link is displayed

function AbrirSecao(secao) {
      let display = document.getElementById('content')
      display.textContent = secao
     }


<select name="unidade" id="unidade" onChange="AbrirSecao(this.value)">
  <option value="">Selecione sua Cidade</option>
  <option value="http://www.google.com.br#one">Sua Cidade 1</option>
  <option value="http://www.google.com.br#two">Sua Cidade 2</option>
</select>
<p id="content"></p>

Instead I needed that when selecting the option the page would load the content of an external page, as below:

<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vehicula 
   tortor metus, laoreet condimentum urna aliquet vitae. Aliquam eu felis 
   malesuada, maximus risus nec, aliquet leo</p>

CodePudding user response:

Unless the websites you want to load data from are on the same domain as yours, you will be blocked by CORS policy.

If you have control over the website servers you need to grab content from, you can use fetch():

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

More on CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Here is an example using fetch() https://jsfiddle.net/v4uL0na2/ The second option returns HTML from the JSFiddle home page. The second option results in an error because of CORS.

    function AbrirSecao(secao) {
      let display = document.getElementById('content')

      fetch(secao).then(function(response) {
        // The API call was successful!
        return response.text();
      }).then(function(html) {
        // This is the HTML from our response as a text string
        var parser = new DOMParser();
        var doc = parser.parseFromString(html, 'text/html');
        const element = doc.querySelector('body > *');
        display.appendChild(element);
      }).catch(function(err) {
        // There was an error
        console.warn('Something went wrong.', err);
      });
    }
<select name="unidade" id="unidade" onChange="AbrirSecao(this.value)">
  <option value="">Selecione sua Cidade</option>
  <option value="/">jsfiddle</option>
  <option value="http://www.google.com.br#two">Sua Cidade 2</option>
</select>
<p id="content"></p>

(The above code sample will not work here)

CodePudding user response:

with Jquery use load(), its simple..

$('#siteloader').load('http://www.your-link.com');

function AbrirSecao(secao) {
  $('#content').load(secao);
}

vanillaJS use fetch. try this :

function AbrirSecao(secao) {
  fetch(secao)
    .then(function(response) {
      return response.text();
    })
    .then(function(body) {
      document.querySelector('#content').innerHTML = body;
    });
}
  • Related