20
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryとPHPでJSONデータをやり取りする

Posted at

jQueryとPHPでJSONデータを扱う時に使う関数はこちらです。

種類 エンコード デコード
jQuery JSON.stringify JSON.parse
PHP json_encode json_decode

jQueryから非同期にサーバーにJSONデータを送信し、
PHPで処理した後、JSONデータを返す場合は、このような処理になります。

jQuery側の処理
$(function() {
	$('#btn').click(function() {
		var testdata = new Object();
		testdata.num = 1;
		testdata.str = 'str';
		testdata.b1 = true;
		testdata.b2 = false;
		testdata.obj = new Object();
		testdata.obj.name = 'obj';
		testdata.ar1 = [ 1, 2, 3 ];
		testdata.ar2 = { name: 'obj1', age: 10 };
		testdata.ar3 = [ { name: 'obj1', age: 10 }, { name: 'obj2', age: 20 }, { name: 'obj3', age: 30 } ];
		var data = JSON.stringify(testdata);
		$.post('index.php', {
			data: data
		}, function(rs) {
			if (rs.contents !== null) {
				$('#contents').html(rs.contents);
			}
		});
	});
});
PHP側の処理
<?php
$html_contents = '';

// testdata.
if (isset($_POST['data'])) {
	$testdata = json_decode($_POST['data']);
	$html_contents .= '<p>num='.$testdata->num.'</p>';
	$html_contents .= '<p>str='.$testdata->str.'</p>';
	$html_contents .= '<p>b1='.($testdata->b1 ? 'true' : 'false').'</p>';
	$html_contents .= '<p>b2='.($testdata->b2 ? 'true' : 'false').'</p>';
	$html_contents .= '<p>obj.name='.$testdata->obj->name.'</p>';
	$html_contents .= '<p>ar1:';
	foreach ($testdata->ar1 as $n) {
		$html_contents .= $n.', ';
	}
	$html_contents .= '</p>';
	$html_contents .= '<p>ar2:';
	foreach ($testdata->ar2 as $k => $v) {
		$html_contents .= $k.' => '.$v.', ';
	}
	$html_contents .= '</p>';
	$html_contents .= '<p>ar3:';
	foreach ($testdata->ar3 as $a) {
		foreach ($a as $k => $v) {
			$html_contents .= $k.' => '.$v.', ';
		}
	}
	$html_contents .= '</p>';
}

$rs = array(
	"contents" => $html_contents,
);

header('Content-Type: application/json; charset=utf-8');
echo json_encode($rs);
結果
num=1

str=str

b1=true

b2=false

obj.name=obj

ar1:1, 2, 3,

ar2:name => obj1, age => 10,

ar3:name => obj1, age => 10, name => obj2, age => 20, name => obj3, age => 30,
20
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?