[ やりたいこと ]
・inputのname属性[id]がpostされていたら非同期で値を返す
testFech内のconsoleが[SyntaxError: Unexpected end of JSON inputat testFech]となってしまいます。
読みにくいコードで申し訳ありませんが、ご教授いただけますと幸いです。
HTML
1<form method="POST" name="user"> 2 <input type="text" name="id"><button id="btn" type="button">送信</button> 3</form>
php
1$array = [ 2 'tokyo' => '東京', 3 'osaka' => '大阪', 4 'aichi' => '名古屋' 5]; 6 7header("Content-Type: application/json; charset=utf-8"); 8$json_array = json_encode($array); 9if(isset($_POST['id'])){ 10 echo($json_array); 11} 12} 13
javascript
1 let btn = document.getElementById('btn'); 2 let input = document.getElementsByName('id')[0]; 3 4 5btn.addEventListener('click',()=>{ 6 let value = input.value; 7 let param = {id_number:value}; 8 9 testFetch(param).then((res)=>{ 10 console.log(res); 11 }); 12}); 13 14 15async function testFetch(param){ 16 const result = await fetch('hoge.php', 17 { 18 method:'POST', 19 headers: { 20 'Content-Type': 'application/json' 21 }, 22 body:JSON.stringify(param) 23 }) 24 console.log(result.json()); 25 }
回答1件
あなたの回答
tips
プレビュー