jQuery と PHP を一緒に使用する方法を学んでいます。初めての試みで、ほぼコンセプトが掴めた感じです。ただし、対処できなかった問題があります。JSON オブジェクトを PHP スクリプトに投稿し、パラメータの 1 つを返そうとすると、次のエラーが表示されます。「オブジェクト以外のプロパティを取得しようとしています ...」
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css"></style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
var myData = {
'firstName' : 'John',
'lastName' : 'Doe'
};
$.ajax( {
type: "POST",
url: "postData.php",
contentType: "application/json",
data: myData,
success: function(msg){
alert(msg);
},
error: function(err) {
alert('error!' + err);
}
});
}
</script>
</body>
</html>
postData.php:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>