我現在正在學習 Ajax,但在查找僅使用 javascript 執行 jquery 所做的事情的視頻或文章時遇到問題。要從 HTML 頁面加載并將其放在頁面上,使用 jquery 就像這樣:
$(function () {
$("#showData").load("pageName.html #whatIWant");
});
并且#whatIWant 中的資料將在具有#showData id 的元素中。感謝您的參與,我不知道如何用 Vanilla Js 做同樣的事情。
注意:如果我使用下面的方法,我會從另一個頁面獲取所有資料,并且我想控制回應。
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);
});
uj5u.com熱心網友回復:
您可以使用內置XMLHttpRequest來獲取 HTML 檔案。
function fetchElement(url, selector) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (!this.responseXML || !this.responseXML.querySelector) reject("No HTML Document found");
else resolve(this.responseXML.querySelector(selector));
}
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.send();
});
}
const myElement = await fetchElement("pageName.html", "#whatIWant");
document.querySelector("#showData").innerHTML = "";
document.querySelector("#showData").appendChild(myElement);
或者,您也可以使用Fetch API來獲取網頁,并使用DOMParser來決議它。
async function fetchElement(url, selector) {
const data = await fetch(url).then(res => res.text());
const parsed = new DOMParser().parseFromString(data, 'text/html');
return parsed.querySelector(selector);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/393293.html
標籤:javascript 查询 阿贾克斯
上一篇:當我使用xcode使用真實的ios設備進行測驗時,react-native-push-notificationremote不顯示
下一篇:如何在HTML中呼叫此函式?
