我想在按钮点击时将一些Jade内容加载到特定的div中。我已经找到了如何使用jQuery进行此操作的方法,有几篇文章提到了这个问题,基本上我想做的是:
$('#div').load('/somePage');
然而,我在我的项目中无法使用jQuery。 是否有等效的函数可以在原生JavaScript中使用?
$('#div').load('/somePage');
然而,我在我的项目中无法使用jQuery。 是否有等效的函数可以在原生JavaScript中使用?
我认为你可以通过以下方式实现:
var request = new XMLHttpRequest();
request.open('GET', '/somepage', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
document.querySelector('#div').innerHTML = resp;
}
};
request.send();
顺便提一下,您也可以使用fetch API完成这个任务。
fetch('/somepage')
.then(function(response) {
return response.text();
})
.then(function(body) {
document.querySelector('#div').innerHTML = body;
});
顺便提一下,你可以阅读这篇博客文章了解关于fetch API的一些内容。
当我试图解决同样的问题时,我根据Ali BARIN的答案制作了这个版本,它似乎非常好用,但是更加明确,增加了init
信息,并且有一些逻辑使用document.getElementById
而不是querySelector
。
/*
* Replicates the functionality of jQuery's `load` function,
* used to load some HTML from another file into the current one.
*
* Based on this Stack Overflow answer:
* https://dev59.com/KloT5IYBdhLWcg3w0SKZ#38132775
* And `fetch` documentation:
* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
*
* @param {string} parentElementId - The ID of the DOM element to load into
* @param {string} htmlFilePath - The path of the HTML file to load
*/
const loadHtml = function(parentElementId, filePath) {
const init = {
method : "GET",
headers : { "Content-Type" : "text/html" },
mode : "cors",
cache : "default"
};
const req = new Request(filePath, init);
fetch(req)
.then(function(response) {
return response.text();
})
.then(function(body) {
// Replace `#` char in case the function gets called `querySelector` or jQuery style
if (parentElementId.startsWith("#")) {
parentElementId.replace("#", "");
}
document.getElementById(parentElementId).innerHTML = body;
});
};
你可以这样做,但是有一些需要注意的地方。
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("Your URL")
.then((resolve) => {
console.log(resolve);
})
.catch((reject) => {
console.error(reject);
});
我想让你注意的是,如果你将URL放到一个页面中,它会将其作为字符串从<html>
返回到</html>
,我猜没有办法像jQuery中的.load()
方法一样只获取其中的一部分。
fetch()
API。 - Pointyfetch
API。 - gcampbell