在前端開發中,有時需要動態取得 HTML 內容。若使用 jQuery,可透過 ajax 方法;若不使用框架,則可用原生 XMLHttpRequest。
需要注意的是,async 設為 false 會讓請求同步執行,雖然能立即取得結果,但會阻塞後續程式碼,現代開發應避免。以下提供 jQuery 與原生寫法供參考。
$.ajax({
async: false,
url: 'aa.html',
success: function (result) {
console.log(result);
}
});var xhr = new XMLHttpRequest();
xhr.open('GET', 'aa.html', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('myDiv').innerHTML = xhr.responseText;
}
};
xhr.send();