发送一个帖子请求和一个PHP文件,将其写入一个文件,用于测试我刚使用过的 发送消息的“虚拟文本”
//FILE - SSE.html
// xmlhttprequest post
//function.................................................
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
console.log("request made");
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("POST","writeToFile.php",true);
xmlhttp.setRequestHeader("Content-type","text/plain;charset=UTF-8");
xmlhttp.send("dummy text");
}
// html body.................................................
<form>
<textarea name="q" onKeyUp="loadXMLDoc()" id="ta1" cols=40 rows=10></textarea>
</form>
<textarea id="ta2" cols=40 rows=10></textarea>
//PHP file.......
<?php
$clientData=$_POST["q"];
$File = "WrittenByPHP.txt";
$Handle = fopen($File, w');
$Data = $clientData;
fwrite($Handle, $Data);
fclose($Handle); ?>
结果在控制台............一些垃圾 值..............................
请求SSE.html:46
(!)注意:未定义的索引:q in C:\ wampnew \ www \ RD \ writeToFile.php在线 4 调用堆栈 #TimeMemoryFunctionLocation 10.0003252112 {main}().. \ writeToFile.php : 0
----------------------------------------------- -----------------------------为什么上面的垃圾代码产生了?提前谢谢。
答案 0 :(得分:0)
检查是否isset()
并退出脚本:
<?php
if(isset($_POST["q"])){
$clientData = $_POST["q"];
$File = "WrittenByPHP.txt";
$Handle = fopen($File, 'w');
$Data = $clientData;
fwrite($Handle, $Data);
fclose($Handle);
die;
}
?>
您应该在帖子中发送q
参数。
var params = "q="+document.getElementById('ta1').value;
xmlhttp.open("POST","ajax.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
形式:
<form>
<textarea name="q" onKeyUp="loadXMLDoc()" id="ta1" cols=40 rows=10></textarea>
</form>
这将在每个onKeyUp
上提交,您应该将其更改为onblur