Ajax load new page
A classic!
To load a new page using AJAX, you can use the XMLHttpRequest
object or the fetch
API. Here's an example of how you can do it:
Using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('GET', 'newpage.html', true);
xhr.onload = function() {
if (xhr.status === 200) {
document.body.innerHTML = xhr.responseText;
}
};
xhr.send();
In this example, we create a new XMLHttpRequest
object and set its open
method to load the newpage.html
file. We set the onload
event handler to a function that will be called when the request is complete. In this function, we check if the request was successful (200 status code) and if so, we update the innerHTML
property of the body
element with the response text.
Using fetch API
fetch('newpage.html')
.then(response => response.text())
.then(html => {
document.body.innerHTML = html;
});
In this example, we use the fetch
API to load the newpage.html
file. We use the then
method to handle the response, which returns a promise that resolves to the response text. We then update the innerHTML
property of the body
element with the response text.
Loading a new page with jQuery
$.ajax({
url: 'newpage.html',
type: 'GET',
success: function(data) {
$('body').html(data);
}
});
In this example, we use the jQuery library to load the newpage.html
file using the ajax
method. We set the url
property to the URL of the new page, the type
property to GET
, and the success
property to a function that will be called when the request is complete. In this function, we update the innerHTML
property of the body
element with the response data.
Loading a new page with a library like jQuery or Axios
import axios from 'axios';
axios.get('newpage.html')
.then(response => {
document.body.innerHTML = response.data;
});
In this example, we use the Axios library to load the newpage.html
file using the get
method. We then update the innerHTML
property of the body
element with the response data.
Remember to replace newpage.html
with the actual URL of the new page you want to load.