dpitqpax07626
2018-11-12 18:17
浏览 220

使用JavaScript在文本文件中写入数据

I'm working on a project to make sure that users finish a video. I would like to have it just add something like "user has finished video" to an already existing text file. Here is what I have in my JavaScript file.

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

and Data.php has

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

As of now, there are no errors in the console, but it does not write the data to the text file.

Please let me know what i'm doing wrong

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drmg17928 2018-11-12 18:29
    已采纳

    Since you are using http.setRequestHeader("content-type", "application/x-www-form-urlencoded");, the request expects the data to be formatted like serialized HTML form data. Change the following line to provide the data in the proper format:

    var data = "data=This%20user%20has%20finished%20the%20video";
    
    点赞 打赏 评论

相关推荐 更多相似问题