test.php
PHP
1<html lang="ja"> 2<body> 3 <div id="text_area"></div> 4</body> 5</html> 6 7<?php 8echo <<<EOM 9<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> 10<script> 11var fn = function() { 12 var result = "NG"; 13 $.ajax({ 14 type: 'post', 15 url: "test1.php", 16 success: function($param_json){ 17 var param = JSON.parse($param_json); 18 result = param.result; 19 } 20 }); 21 document.getElementById('text_area').innerHTML = result; 22}; 23fn(); 24</script> 25EOM; 26?>
test1.php
PHP
1<?php 2$param = array( 3 "result" => "OK" 4); 5$param_json = json_encode($param); 6echo $param_json; 7?>
結果
NG
エラーメッセージ
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (test.php:16:21)
at c (jquery.min.js:2:28327)
at Object.fireWith [as resolveWith] (jquery.min.js:2:29072)
at l (jquery.min.js:2:79901)
at XMLHttpRequest.<anonymous> (jquery.min.js:2:82355)
success @ test.php:16
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
l @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
load (async)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
fn @ test.php:12
(anonymous) @ test.php:22
【質問】
どういうことでしょうか?
追記
呼び出し元をhtmlにすると動きます。
回答2件
あなたの回答
tips
プレビュー