我的项目是从用户那里获取输入,并使用ajax和php将其写入JSON格式的文本文件的末尾。问题是php只将时间和日期写入文件的末尾而没有其他内容。我从之前的帖子中取了示例并在此处修改它以用于我的目的。这是html movie.html:
<html lang="en">
<head>
<meta charset="utf-8"/>
<script src="movie.js" type="text/javascript"></script>
</head>
<body>
<h1>
<center>
<input id="box" type="textbox"name="box" value="Enter Movie:"/>
<input id="add" type="button" value="Submit" onClick="addStuff();" /></center>
</h1>
<div id="status" ></div>
<h2>MOVIE NAME:</h2>
<ul id="list" name="list">
</ul>
<div id="status"></div>
</body>
</html>
这是通过Ajax发送数据的movie.js文件:
function addStuff(){
var movie_name_entered = document.getElementById("box").value;
var movieList = document.getElementById("list");
var hr= new XMLHttpRequest();
var url= "movie.php";
hr.open("POST",url,true);
hr.setRequestHeader("Context-type","application/x-www-form-urlencoded");
var param = "film=" + movie_name_entered;
hr.setRequestHeader("Content-length", param.length);
hr.setRequestHeader("Connection", "close");
hr.onreadystatechange= function(){
if(hr.readyState==4 && hr.status==200){
var return_data=hr.responseText;
console.log(hr.responseText);
document.getElementById("status").innerHTML=return_data;
}
}
hr.send(param);
document.getElementById("status").innerHTML = "processing...";
}
这里是php(顺便说一下,我控制台。记录了发送到php的数据,这是正确的):
<?php
if($_POST){
$data = $_POST["film"];
$file ='movie.txt';
$fp = fopen($file, "a");
$encoded = json_encode($data);
fwrite($fp, $encoded);
fclose($fp);
return $encoded;}
?>
如上所述,代码只将时间和日期写入文本文件,而不管我做什么。我测试了发送的数据及其有效的$ _POST数据。我不确定如何继续下去。任何帮助将不胜感激。 THX!
答案 0 :(得分:1)
在movie.js中尝试此代码
function addStuff() {
var movie_name_entered = document.getElementById("box").value;
var movieList = document.getElementById("list");
var hr = new XMLHttpRequest();
var url = "movie.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "film=" + movie_name_entered;
hr.setRequestHeader("Content-length", param.length);
hr.setRequestHeader("Connection", "close");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
console.log(hr.responseText);
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(param);
document.getElementById("status").innerHTML = "processing...";
}
请将您的PHP代码更改为
if ($_POST) {
$data = $_POST["film"];
$file = 'movie.txt';
$fp = fopen($file, "a+");
$encoded = json_encode($data);
fwrite($fp, $encoded);
fclose($fp);
exit();
}
答案 1 :(得分:0)
你得到一个空的$_POST
变量,所以你的php代码永远不会被执行。你的代码中有错误:
hr.setRequestHeader("Context-type","application/x-www-form-urlencoded");
应为Content-type
,将x
替换为c
:D