const b1 = document.getElementById("btn1");
const b2 = document.getElementById("btn2");
b1.addEventListener("click", () =>
{
loadText();
});
b2.addEventListener("click", () =>
{
clearText();
});
function loadText()
{
fetch('js19_txt_en.txt')
.then(response =>
{
if (!response.ok)
{
throw new Error('Network response was not ok');
}
return response.text();
})
.then(text =>
{
// Process text data 'text'
const d1 = document.getElementById("text");
d1.textContent = text;
})
.catch(error =>
{
// Error Handling
console.error('There has been a problem with your fetch operation:', error);
});
}
function clearText()
{
const d1 = document.getElementById("text");
d1.textContent = "";
}
Explanation
fetch('js19_txt_en.txt')
The fetch function sends an HTTP request and returns a Promise representing the result. The then method is called when the Promise is resolved (if the request is successful). Then, the callback function passed to then is executed. The argument of the callback function passed to then is a Response object representing the fetch result. This Response object contains information such as the response status code, headers, and body.
.then(response => { ... })
In this example, the argument name of then is set to "response". You can freely set the argument name of the then method. Also, it can be anything as long as it is a valid variable name.
Receive the response from the fetch function and execute the process. Check whether the HTTP status code is in the 200 range with response.ok. *If there is an error, throw new Error() to generate an error and handle it in the catch() block.
Read the response body as text data with response.text(). *The ".text()" in xxx.text() is a method provided to read text. Since it returns a Promise, processing continues with then().
.then(text => { ... })
The result of "return response.text();" is passed to the argument name "text" of then. The text variable name here can be a different name. In this example, text data is displayed in the textarea tag.
.catch(error => { ... });
Executed if an error occurs during execution of fetch() or processing within then(). An example of displaying an error message in the console.
Since fetch is executed asynchronously, it is necessary to connect the processing with then or catch().