前提
PHPとjavascriptで非同期通信を実装しています。
想定している挙動と実際の挙動
セレクトボックスで選んだ値に該当するデータを外部のテキストファイルから呼び出してコンソールに出力させたい。
しかし現状は1番上の「test」のデータしか取得できない。
該当のソースコード
php
1<?php 2if(isset($_POST['name'])){ 3 $fp = fopen('test.txt', 'r'); 4 while(1){ 5 $str = chop(fgets($fp)); 6 if($str == "") exit; 7 if($_POST['name'] == explode(",", $str)[0]) echo $str; exit; 8 } 9} 10?>
html
1html> 2<head> 3<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 4<meta http-equiv="Content-Script-Type" content="text/javascript"> 5<title>テスト</title> 6</head> 7 8<body> 9 10<form> 11<select id="test" name="test"> 12<option value="">---</option> 13<option value="test">test</option> 14<option value="あああ">あああ</option> 15<option value="テスト">テスト</option> 16</select> 17<input type="button" id="sender" name="sender" value="送信"> 18</form> 19 20<script type="text/javascript"> 21document.querySelector('#sender').addEventListener('click', GetAddr); 22 23function GetAddr(){ 24 let xhr = new XMLHttpRequest(); 25 let fd = new FormData(); 26 27 fd.append('name', document.querySelector('#test').value); 28 29 xhr.open('POST', './regi.php', true); 30 xhr.onload = function(){ 31 if(xhr.readyState == 4 && xhr.status == 200){ 32 console.log(xhr.responseText); 33 } 34 } 35 xhr.send(fd); 36} 37</script> 38 39</body> 40 41</html>
text
1test,test,テスト 2あああ,あああ,aaaa 3いいい,いいい,iiii 4テスト,TEST,テ
試したこと
半角文字しかうまく動かないので文字コードを疑いましたが全てUTF-8のファイルでした。
また、javascriptで送信した値をすぐphp側でechoした際文字化けしていました。