I’m learning Ajax now and I have a problem finding videos or articles that use just javascript to do things that jquery does.
To load apart from an HTML page and put it on the page, using jquery it is just like that :
$(function () {
$("#showData").load("pageName.html #whatIWant");
});
And the Data in #whatIWant will be in element with #showData id.
I can’t figure how to do the same thing with Vanilla Js
thanks for your participation.
NOTE :
If I use the method below, I get all the data from the other page and I want to control the response.
const getData = (url) => {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.onload = function () {
if (this.readyState === 4 && this.status === 200) {
resolve(this.responseText);
} else {
reject(this.responseText);
}
};
request.open("get", url, true);
request.send();
});
};
getData("test.html")
.then((resolve) => {
console.log(resolve);
})
.catch((reject) => {
console.error(reject);
});
2
Answers
There is another way that I found when seeking answers.
This Answers and the other one up are both works for me, I hope these answers help someone.
You can use the built in
XMLHttpRequest
to fetch an HTML document.Alternatively, you can also use the Fetch API to fetch the web page, along with the DOMParser to parse it.