XHR is an older technique. All modern browsers support the
Fetch API[
^], which is much nicer to work with. Especially if you combine it with
async/await[
^].
For example:
let abortController = null;
async function loadSearchResults() {
if (abortController) {
abortControler.abort("Reload");
}
const keyword = inputField.value.trim();
if (keyword.length === 0) {
return;
}
abortController = new AbortController();
searchLoading.style.display = "block";
try {
const url = new URL("https://[REDACTED]/ajax/movie/search");
url.searchParams.set("keyword", keyword);
const response = await fetch(url, {
credentials: "same-origin",
signal: abortController.signal
});
if (!response.ok) {
const responseText = await response.text();
console.error(response.status, response.statusText, responseText);
return;
}
const searchResults = await response.json();
} catch (e) {
console.error(e);
} finally {
abortController = null;
searchLoading.style.display = "none";
}
}
document.getElementById("sch").addEventListener("click", loadSearchResults);
Now you just need to fill in the "TODO" blocks. You might want to consider using a templating language like
Handlebars[
^] to transform the search results into an HTML fragment.