我一直在努力使用 Ajax 编写服务器文本文件,如果有人花点时间看一下,我将不胜感激。简单来说,为什么下面的代码不将“testdata”写入test1.txt?
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert('done')
}
}
xmlhttp.open("POST","test1.txt",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("testdata");
</script>
</head>
<body>
</body>
</html>
我已经成功地能够使用 GET 读取文本文件。如果我将 3 个关键行替换为
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
它有效。
上面的代码有什么问题或者这是文件权限问题?我正在使用 GoDaddy 并获得了写入权限,以便我可以使用 php 等修改上述文本文件。
非常感谢任何帮助。
提前致谢!
乔尔
最佳答案
现在可以工作了 - 谢谢亚历克斯!这些是工作文件:
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert('done')
}
}
xmlhttp.open("POST","phpwrite2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=Joel");
</script>
</head>
<body>
</body>
</html>
和 PHP:
<?php
$myFile = "ttt.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_POST["name"];
fwrite($fh, $stringData);
fclose($fh);
?>
关于javascript - 使用 Ajax 编写服务器文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26961750/