使用XMLHttpRequest传递数据时获取未定义的数组键



我正试图将一个格式化的长文本字符串传递给php进程以保存到文件中。我使用POST方法,因为字符串可能很长。它似乎在整个过程中运行,并返回消息"文件已保存",但带有错误消息"未定义数组键";数据"在php代码的第2行。该文件不会被保存,也不会从前面的函数中的XMLHttpRequest发送任何数据。我的代码是:-这从上一个函数中获取"str",并且格式正确。

function getGame(str){
//Sends data to the php process "saveGame.php".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data); 
} 

然后转到"saveGame.php",问题出现在第2行。

<?php
$outputString = $_POST["data"];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$fp = fopen("C:\xampp\htdocs\BowlsClub\GamesSaved\test26.txt","w");
fwrite($fp, $outputString);
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
$message = "File saved!"; 
}
fclose($fp);
echo $message;
?>

我认为我的过程代码是可以的,但通过";数据";变量,我不确定它是什么。

我测试了文件保存过程。我放了一个伪字符串作为'outputString'的值,它保存了它。当我返回并使用当前代码时,文件被覆盖并为空,表明它保存了一个空字符串。因此,尽管文件的保存是有效的,但似乎没有数据被传递到saveTeams.php。

下面我有一个可复制的例子。如果您将它与saveTeams.php文件一起使用,并且有一个文件试图将数据保存到它,则应在警报下拉列表中显示我得到的错误。

<!DOCTYPE html>

<head>
<title>Test program</title>

<script language="javascript">
function formatOutput() {
// lots of formatting goes on here

var formattedText = "This is a test";   //test data               
getGame(formattedText);
}
function getGame(str){
//Sends data to the php process "save Game".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data); 
}

</script>
</head>
<body>
<table width="1000" align="center" border="0">
<br />
<tr>
<td width="500"align="center" colspan="3" <button onclick="formatOutput()"/>Click on me</td>
</tr>
</table>


</body>
</html>

希望一切顺利。我对此有点陌生。

您缺少一个post-key

试着把这条线路改成

var data='data='+str;

最新更新