JavaScriptを使ったSPA(Single Page Application)の実装
クライアント側でJavaScriptを使い、SPA(Single Page Application)を実装する方法です。
サーバ側
本サンプルではサーバ側をNode.js+Expressで作成します。
サーバ側ではクライアントからの要求で更新するデータを送付するルーティングを記載します。
app.post('/post-test', (request, response) => {
const { sendData } = request.body;
const result = sendData + " to server."
response.send({ result: result });
});
クライアント側
jQueryを使う場合と素のJavaScriptを使う方法があります。
jQuery
$.post('/post-test', { sendData: 'client' })
.done((data) => {
if (data.result) {
console.log(data.result); // client to server.
return;
}
});
素のJavaScript
Fetch APIを使います。
const data = {
sendData: 'client'
};
fetch('/post-test', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
}).then((response) => {
if (!response.ok) {
throw('server error');
return;
}
return response.json();
}).then((data) => {
// data = response.json()の結果.
if (data.result) {
console.log(data.result); // client to server.
return;
}
}).catch((error) => {
console.error(error);
});
今回は文字列の送信だけですが、リストのデータなどをサーバから送信することでページの表示を切り替えることが可能です。