使用JSON在php中附加文本文件,不工作且不显示错误消息

时间:2017-07-17 12:34:35

标签: javascript php json ajax

我有一个JavaScript函数,当有人点击div时,会使用参数调用它。 JavaScript函数从参数中生成一个JSON字符串,然后对获取此JSON字符串的php文件进行XMLHttpRequest(AJAX),找到JSON字符串中的数字,然后将该数字存储在服​​务器上的文本文件中。

然而,当我在我的服务器上运行它时,没有数字附加到文本文件,似乎没有任何事情发生。没有显示错误消息。 "谢谢!"消息确实显示在div中,这意味着readystate变为4,状态变为200.

使用参数调用JavaScript函数的html代码:

<li id="star1" onclick="saveRating(1)"><i class="fa fa-star" aria-hidden="true"></i></li>

创建JSON字符串并调用php文件的javaScript函数:

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文件,在JSON字符串中搜索数字并将数字附加到文本文件中:

<?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);
?>

[edit]文本文件和PHP文件都具有写入权限。

1 个答案:

答案 0 :(得分:1)

我在你的剧本中发现了2个错误。

  1. 将文件句柄放在给定的行中 while(false!==($ char = fgetc($ myfile))){

  2. $ myfile = fopen(“ratingNumbers.txt”,“a +”); //开放阅读和写作;