divをクリックしたときにパラメータで呼び出されるJavaScript関数があります。 JavaScript関数はJSON文字列をパラメータから外し、このJSON文字列を受け取り、JSON文字列内の番号を見つけてサーバ上のテキストファイルに格納するPHPファイルにXMLHttpRequest(AJAX)を行います。JSONを使用してPHPでテキストファイルを追加していますが、エラーメッセージは表示されません。
私はこれを私のサーバー上で実行すると、テキストファイルに数字が追加されず、何も起こらないようです。エラーメッセージは表示されません。 「ありがとうございました!」メッセージはreadyStateのが4になるん意味のdivに表示されますないとステータスが200
パラメータでJavaScript関数を呼び出すHTMLコードになるん:
<li id="star1" onclick="saveRating(1)"><i class="fa fa-star" aria-hidden="true"></i></li>
JavaScript関数を作成しますJSON文字列とPHPファイルを呼び出します:番号のJSON文字列を検索し、テキストファイルに番号を付加し、
function saveRating(num){
obj = { "score":num };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//a "Thank You!" message is displayed in the div
}
};
xmlhttp.open("GET", "php/storeRating.php?x=" + dbParam, true);
xmlhttp.send();
}
テキストファイルを開き、PHPファイルを:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false); //gets the param that was sent and stores it in $obj
//opens text file and sets to appending the file.
$myfile = fopen("ratingNumbers.txt", "a");
//goes through string and if it finds a number it adds it to the text file.
while(false !== ($char = fgetc($obj))){
if($char == 1){
fwrite($myfile, $char);
}if($char == 2){
fwrite($myfile, $char);
}if($char == 3){
fwrite($myfile, $char);
}if($char == 4){
fwrite($myfile, $char);
}if($char == 5){
fwrite($myfile, $char);
}
}
//closes the file
fclose($myfile);
?>
[編集]テキストファイルとPHPファイルの両方に書き込み権限があります。
mmmファイルが書き込み可能であることを確認してください。デバッグ用のPHPのエコーも良いでしょう。 error_reporting(E_ALL); ini_set( 'display_errors'、1);すべてのPHPエラー –
'fgetc($ obj)'を表示しますか? $ objはファイルハンドルではありません – Musa
ええ、テキストファイルとPHPファイルは書き込み可能な権限を持っています。最初のポイントに応じて –