0

发送一个发布请求和一个 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 ( ! ) 注意:未定义索引:第4
行 C:\wampnew\www\RD\writeToFile.php 中的 q调用堆栈 #TimeMemoryFunctionLocation 10.0003252112{main}( )..\writeToFile.php : 0

-------------------------------------------------- -------------------------- 为什么会出现上面的垃圾代码?提前谢谢。

4

1 回答 1

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

于 2012-10-03T08:16:32.067 回答