現在の言語: 日本語

戻る

入れ子になった配列データ
ajax

ajaxを使用してhtml側からサーバーにリクエストします。
サーバーではphpで判定した結果をhtml側で受け取ります。
このサンプルではプリフライトリクエストを使用した入れ子になった配列データの例となります。

[サンプル]

copy
[test3.html(javascript)]
document.getElementById('sendArrayButton').addEventListener('click', () => {
	const dataToSend = {
		name: 'どうぶつ',
		kind: ['ねこ', 'いぬ'], // 配列
		details: {
			color: ['白', '黒', '茶'],
			sound: ['にゃあ', 'わん']
		}
	};

	fetch('http://localhost/test3.php', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
		},
		body: JSON.stringify(dataToSend), // JavaScriptオブジェクトをJSON文字列に変換
	})
	.then(response => {
		if (!response.ok) {
			throw new Error('ネットワークエラーが発生しました');
		}
		return response.json(); // PHPからのJSONレスポンスをJavaScriptオブジェクトに変換
	})
	.then(data => {
		console.log('PHPからのレスポンス:', data);
		// レスポンスの表示例
		const resultDiv = document.getElementById('result');
		if (data.status === 'success') {
			resultDiv.innerHTML = `
				<p>名前: ${data.receivedData.name}</p>
				<p>種類: ${data.receivedData.kind.join(', ')}</p>
				<p>色: ${data.receivedData.details.color.join(', ')}</p>
				<p>音: ${data.receivedData.details.sound.join(', ')}</p>
			`;
		} else {
			resultDiv.textContent = `エラー: ${data.message}`;
		}
	})
	.catch(error => {
		console.error('Fetchエラー:', error);
		document.getElementById('result').textContent = `リクエストに失敗しました: ${error.message}`;
	});
});
[test3.php]
// レスポンスの形式をJSONに設定
header('Content-Type: application/json');

// POSTされたJSONデータを取得
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true); // trueを指定すると連想配列としてデコードされる

// 受信したデータを検証(例)
if (!isset($data['name']) || !is_array($data['kind'])) {
    echo json_encode(['status' => 'error', 'message' => 'データが不足しているか、形式が不正です。']);
    exit;
}

// 受信したデータをログに出力(デバッグ用)
error_log('受信データ: ' . print_r($data, true));

// 受信した配列データにアクセス
$name = $data['name'];
$kind = $data['kind']; // PHPの配列としてアクセス可能
$color = $data['details']['color']; // 入れ子になった配列にもアクセス可能
$sound = $data['details']['sound']; // 入れ子になった配列にもアクセス可能
$ary1=[];
$ary2=[];
//色という文字を追加
for($i=0; $i < count($sound); ++$i)
{
    $ary1[]=$color[$i]."色";
}
//鳴き声をリピート追加
for($i=0; $i < count($sound); ++$i)
{
    $ary2[]=$sound[$i].$sound[$i];
}
// ここでhtmlに返すための判定やデータの準備などを行います
$data["name"]="動物の種類";
$data["kind"]=array("ねこちゃん,わんちゃん");
$data['details']['color']=$ary1;
$data['details']['sound']=$ary2;

// 受信したデータをそのまま返す例(または処理結果を返す)
echo json_encode([
    'status' => 'success',
    'message' => 'データを受信しました。',
    'receivedData' => $data // 受信したデータをそのまま返す
]);
copy
[test3.html(javascript)]
document.getElementById(‘sendArrayButton’).addEventListener(‘click’, () => {
    const dataToSend = {
        name: ‘Animal’,
        kind: [‘cat’, ‘dog’], // Array
		details: {
            color: [‘white’, ‘black’, ‘brown’],
            sound: [‘meow’, ‘woof’]
        }
    };

    fetch(‘http://localhost/test3.php’, {
        method: ‘POST’,
        headers: {
			'Content-Type': ‘application/json’,
        },
        body: JSON.stringify(dataToSend), // Convert JavaScript object to JSON string
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(‘Network error occurred’);
        }
		return response.json(); // Convert JSON response from PHP to JavaScript object
    })
    .then(data => {
        console.log(‘Response from PHP:’, data);
        // Example response display
        const resultDiv = document.getElementById(‘result’);
		if (data.status === ‘success’) {
    resultDiv.innerHTML = `
        <p>Name: ${data.receivedData.name}</p>
        <p>Type: ${data.receivedData.kind.join(‘, ’)}</p>
				<p>Color: ${data.receivedData.details.color.join(‘, ’)}</p>
                <p>Sound: ${data.receivedData.details.sound.join(‘, ’)}</p>
            `;
        } else {
            resultDiv.textContent = `Error: ${data.message}`;
        }
    })
    .catch(error => {
        console.error(‘Fetch error:’, error);
        document.getElementById(‘result’).textContent = `Request failed: ${error.message}`;
    });
});
[test3.php]
// Set response format to JSON
header(‘Content-Type: application/json’);

// Retrieve POSTed JSON data
$json_data = file_get_contents(“php://input”);
$data = json_decode($json_data, true); // Specifying true decodes as an associative array

// Validate received data (example)
if (!isset($data[‘name’]) || !is_array($data[‘kind’])) {
    echo json_encode([‘status’ => ‘error’, ‘message’ => ‘Data is missing or invalid.’]);
    exit;
}

// Output received data to log (for debugging)
error_log(‘Received data: ’ . print_r($data, true));

// Access the received array data
$name = $data[‘name’];
$kind = $data[‘kind’]; // Accessible as a PHP array
$color = $data[‘details’][‘color’]; // Access to nested arrays is also possible
$sound = $data[‘details’][‘sound’]; // Access to nested arrays is possible
$ary1=[];
$ary2=[];
// Add the text “color”
for($i=0; $i < count($sound); ++$i)
{
    $ary1[]=$color[$i].“ color”;
}
// Add sound repeats
for($i=0; $i < count($sound); ++$i)
{
    $ary2[]=$sound[$i].$sound[$i];
}
// Here we perform checks and prepare data for returning to HTML
$data[“name”]=“Animal Type”;
$data[“kind”]=array(“kitty,puppy”);
$data[‘details’][‘color’]=$ary1;
$data[‘details’][‘sound’]=$ary2;

// Example returning received data as-is (or returning processed results)
echo json_encode([
    ‘status’ => ‘success’,
    ‘message’ => ‘Data received.’,
    ‘receivedData’ => $data // Return received data as-is
]);

fetch('http://localhost/test3.php', {
PHPファイルと連携するURLを指定します

method: 'POST',
POST形式を指定しています。

headers: {
'Content-Type': 'application/json',
送信するデータの形式を指定します。

const dataToSend = {
name: 'どうぶつ',
kind: ['ねこ', 'いぬ'], // 配列
details: {
color: ['白', '黒', '茶'],
sound: ['にゃあ', 'わん']
}
};
オブジェクト・リテラルという方法で作成された「オブジェクト」です。
プロパティ(フィールド)と値の組み合わせのデータを送信しています。
detailsにオブジェクト・リテラルで入れ子にしたデータを使用して配列の入れ子のように使用しています。

.then(response => {
response オブジェクトを受け取ります。

return response.json();
データ本体を読み込む指示を出します。

.then(data => {if (data.status === 'success')
非同期で実行されます。
response.json() が完了したときに
引数のdata(実際に読み込まれたJSONデータ)を受け取ることができます。
data.receivedData.details.sound
detail配列に入れ子にしたsound配列を取得しています。




戻る

著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。