Q&A
実現したいこと
(1) と (2) で、my_json_encode() の挙動が違う理由を知りたいです。
前提
(1) 訪問時
index.php で取得されるコメント ($comment_arr_init)
↓
echo の際に my_json_encode() を使うと
途中で途切れてしまい set_comment_html() が実行できません
(2) ajax時
ajax.php で取得されるコメント (comment_arr_ajax)
↓
echo の際に my_json_encode() を使うと
問題なく set_comment_html() が実行できます
該当のソースコード
▼ index.php
php
1<?php 2 /* index.php */ 3 require '/home/public_html/example.com/functions.php'; 4 $res = get_comments(); 5 $comment_arr_init = $res['comment_arr']; 6?> 7<!DOCTYPE html> 8<html> 9<head> 10<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js'></script> 11<script> 12 // ここで my_json_encode を使うと途中で途切れてしまう 13 // const comment_arr_init = <?php echo my_json_encode($comment_arr_init); ?>; 14 const comment_arr_init = <?php echo json_encode($comment_arr_init); ?>; 15</script> 16</head> 17<body> 18 19 <p>comment_init</p> 20 <ul id="comment_init"> 21 <!-- set_comment_html()でセット --> 22 </ul> 23 24 <p>comment_ajax</p> 25 <ul id="comment_ajax"> 26 <!-- set_comment_html()でセット --> 27 </ul> 28 29 <button type="button" id="ajax_get_comments">ajax_get_comments</button> 30 31 <script> 32 // 訪問時のコメントをセット 33 set_comment_html('comment_init', comment_arr_init); 34 35 // ajaxでコメントをセット 36 $(document).on('click', '#ajax_get_comments', function() { 37 $.ajax({ 38 url : 'https://example.com/ajax.php', 39 type : 'POST', 40 dataType: 'json', 41 data : { 42 ajax_func: 'get_comments', 43 } 44 }) 45 .done(function(ajax_res) { 46 // ここでは my_json_encode を使っても問題ない 47 const comment_arr_ajax = ajax_res.comment_arr; 48 set_comment_html('comment_ajax', comment_arr_ajax); 49 }); 50 }); 51 52 // コメントをセット 53 function set_comment_html(id_name, comment_arr){ 54 const lis = comment_arr.map(comment=>{ 55 return `<li><p>${h(comment.text)}</p></li>`; 56 }).join(''); 57 $('ul#'+id_name).html(lis); 58 } 59 60 // エスケープ 61 function h(data) { 62 if (typeof data !== 'string' || !data ) return data; 63 const patterns = { 64 '&': '&', 65 "'": ''', 66 '"': '"', 67 '<': '<', 68 '>': '>', 69 }; 70 return data.replace(/(&|'|"|<|>)/g, function(match) { 71 return patterns[match]; 72 }); 73 } 74 </script> 75 76</body> 77</html>
▼ functions.php
php
1<?php 2function my_json_encode($data) { 3 // 改行, 日本語, スラッシュエスケープしない 4 return json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); 5} 6 7function get_comments(){ 8 // DBから次のコメント一覧が取得されたと仮定 9 return [ 10 'status' => 'ok', 11 'comment_arr' => [ 12 ["id"=>1, "text"=>"hello", "is_official"=>true], 13 ["id"=>1, "text"=>"<script>alert('hi');</script>", "is_official"=>true] // XSSの危険 14 ] 15 ]; 16}
▼ ajax.php
php
1<?php 2/* ajax.php */ 3require '/home/public_html/example.com/functions.php'; 4$ajax_func = filter_input(INPUT_POST, 'ajax_func'); 5echo my_json_encode($ajax_func());
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2023/04/05 16:53