jQuery入門 - Ajax通信
Ajax通信
jQueryを使ってAjax通信を実装する方法を学びます。
タスク
GETリクエスト
$.ajax()メソッドを使ってGETリクエストを実装します
POSTリクエスト
$.ajax()メソッドを使ってPOSTリクエストを実装します
エラーハンドリング
Ajax通信のエラーハンドリングを実装します
ヒント
jQueryのAjaxメソッドを使ってサーバーとの通信を実装しましょう。
参考コード
$(document).ready(function() { // モックAPIのベースURL const API_URL = 'https://jsonplaceholder.typicode.com'; // 1. GETリクエスト $('#get-items').click(function() { $.ajax({ url: API_URL + '/posts', method: 'GET', success: function(response) { const itemList = $('#item-list'); itemList.empty(); response.slice(0, 5).forEach(function(item) { itemList.append( '<div class="item">' + '<strong>' + item.title + '</strong><br>' + 'カテゴリー: ' + item.id + '</div>' ); }); $('#get-log').text('人気一覧を取得しました: ' + new Date().toLocaleTimeString()); }, error: function(xhr, status, error) { $('#get-log').text('エラーが発生しました: ' + error); } }); }); // 2. POSTリクエスト $('#create-item').click(function() { const title = $('#title-input').val(); const category = $('#category-input').val(); if (!title || !category) { $('#post-log').text('タイトルとカテゴリーを入力してください'); return; } $.ajax({ url: API_URL + '/posts', method: 'POST', data: { title: title, body: category }, success: function(response) { $('#post-log').text( 'アイテムを追加しました:\n' + 'ID: ' + response.id + '\n' + 'タイトル: ' + response.title + '\n' + 'カテゴリー: ' + response.body ); $('#title-input').val(''); $('#category-input').val(''); }, error: function(xhr, status, error) { $('#post-log').text('エラーが発生しました: ' + error); } }); }); // 3. エラーハンドリング $('#error-test').click(function() { $.ajax({ url: API_URL + '/invalid-endpoint', method: 'GET', success: function(response) { $('#error-log').text('リクエスト成功: ' + response); }, error: function(xhr, status, error) { $('#error-log').text( 'エラーが発生しました:\n' + 'ステータス: ' + status + '\n' + 'エラー: ' + error ); } }); }); });