やりたいこと
PHPファイルでDBから取得したデータをJSON形式に変換。その後、JQueryファイルでJSONをパースしたい。
初心者なので、実際のコードで教えていただけたら幸いです。
PHPファイル
php
1$dbh = new PDO($dsn,$user,$password); 2 3//ページID 4if($_GET["blog"]){ 5 $get_prm = $_GET["blog"]; 6 $sql = <<<EOF 7select * 8from aging_table 9where trouble_id = $get_prm 10EOF; 11 $stmt = $dbh->query($sql); 12 $res = $stmt->fetchAll(); 13 foreach($res as $rs){ 14 $json = <<<EOF 15{"trouble_id":"{$rs["trouble_id"]}", 16EOF; 17 } 18 //jsonデータの最初と最後に[]をつける処理 19 $json = substr($json,0,-1); 20 $json = "[".$json."]"; 21 //END 22 $res = $json; 23 print_r($res); 24}
HTMLファイル
jQuery
1 $(function(){ 2 $.ajax({ 3 type : "POST", 4 url : "aging_trouble_detail.php", 5 data : "type=hide", 6 success : function(res){ 7 console.log(res); 8 res = JSON.parse(res); 9 $(res).each(function(ind,obj){ 10 }); 11 }, 12 }); 13 }); 14
エラー
HTML
1SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data[詳細] 2
確認したこと
・PHPでのprint_r($res);での結果は[{"trouble_id":"8"]
・jQueryでのconsole.log(res);の結果は、ページ全体ののURLと上記エラーが表示
・検証ツールでネットワークを確認したところ、正常に通信がされ、type=hideは渡っていました。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/27 10:53