使用JavaScript将数据写入文本文件

时间:2018-11-12 18:17:12

标签: javascript php html ajax

我正在研究一个项目,以确保用户完成视频。我想让它只是向现有文本文件中添加“用户已完成视频”之类的内容。 这是我的JavaScript文件中的内容。

    var video = document.getElementById("video");

var timeStarted = -1;
var timePlayed = 0;
var duration = 0;
// If video metadata is laoded get duration
if (video.readyState > 0)
getDuration.call(video);
//If metadata not loaded, use event to get it
else {
video.addEventListener('loadedmetadata', getDuration);
}
// remember time user started the video
function videoStartedPlaying() {
timeStarted = new Date().getTime() / 1000;
 }

function videoStoppedPlaying(event) {
// Start time less then zero means stop event was fired vidout start event
if (timeStarted > 0) {
    var playedFor = new Date().getTime() / 1000 - timeStarted;
    timeStarted = -1;
    // add the new ammount of seconds played
    timePlayed += playedFor;
}
document.getElementById("played").innerHTML = Math.round(timePlayed) + "";
// Count as complete only if end of video was reached
if (timePlayed >= duration && event.type == "ended") {
    document.getElementById("status").className = "complete";
}
}

function getDuration() {
duration = video.duration;
document.getElementById("duration").appendChild(new Text(Math.round(duration) + ""));
console.log("Duration: ", duration);
}

video.addEventListener("play", videoStartedPlaying);
video.addEventListener("playing", videoStartedPlaying);

video.addEventListener("ended", videoStoppedPlaying);
video.addEventListener("pause", videoStoppedPlaying);



var data = "This user has finished the video";
var url = "data.php";
var http = new XMLHttpRequest();
http.open("POST", url, true);

//sends hearder info along with the request
http.setRequestHeader("content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
    alert(http.responseText);

}
}
http.send(data);

而Data.php具有

    <?php
    $data = $_POST['data'];
    $file = fopen('names.txt', 'a');
    fwrite($file, $data);
    fclose($file);
    ?>

到目前为止,控制台中没有错误,但是它不会将数据写入文本文件。

请让我知道我在做什么错

1 个答案:

答案 0 :(得分:0)

由于您使用的是http.setRequestHeader("content-type", "application/x-www-form-urlencoded");,因此该请求期望data的格式类似于序列化的HTML表单数据。更改以下行以提供正确格式的data

var data = "data=This%20user%20has%20finished%20the%20video";