jQueryからJSONを使ってPOST送信
デザインとデータ操作を分離汁。という世間の声がうるさいので
デザイン部分はHTML+JavaScript(jQuery)な環境にしようと思う。
jQueryからGETやPOSTしてスクリプト言語で生成されたJSONを食うサンプルは
よく見るが逆はあまり見ないので備忘録を兼ねて....φ(・ω・` )カキカキ
json形式のデータをjQuery.ajaxを使ってPOST
send_json.js
var func_send_json = function(){ var json_data { id:'epy0n0ff', pw:'hogehoge' }; $.ajax( { url:'receive_json.php', type:'POST', data:json_data, error:function(){}, complete:function(data){alert(data.responseText)}, dataType:'json' } ); } jQuery('button#regist').live("click",func_send_json );
受信したPOSTデータを見てみる
<?php header("Content-Type:text/html; charset=utf-8"); print_r($_POST); ?>
stdout
Array( [id] => epy0n0ff [pw] => hogehoge )
{ id:'epy0n0ff', pw:'hogehoge'}な文字列がPHP側にそのまま渡るのかと思ったら
$_POSTに入れられてるとは...
追記(20011/05/21)
hztのご指摘通りデフォルトはapplication/x-www-form-urlencodedで送信されるので
POSTすればPOST変数になるようです。
jQuery.ajax()より引用
contentTypeString Default: 'application/x-www-form-urlencoded' When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.