【发布时间】:2017-07-17 21:23:24
【问题描述】:
我有一个 JavaScript 函数,当有人单击 div 时,它会使用参数调用。 JavaScript 函数从参数中生成一个 JSON 字符串,然后向接受此 JSON 字符串的 php 文件发出 XMLHttpRequest (AJAX),在 JSON 字符串中查找数字,然后将数字存储在服务器上的文本文件中。
但是,当我在我的服务器上运行此程序时,文本文件中没有附加任何数字,似乎什么也没有发生。不显示错误消息。 “谢谢!”消息确实会显示在 div 中,这意味着 readystate 确实变为 4,status 确实变为 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);
?>
[编辑] 文本文件和 PHP 文件都有写权限。
【问题讨论】:
-
mmm,检查文件是否可写。用于调试的 php 中很少有回声会很好。错误报告(E_ALL); ini_set('display_errors', 1);将显示所有 php 错误
-
fgetc($obj)? $obj 不是文件句柄 -
是的,文本文件和php文件都有可写权限。
标签: javascript php json ajax