我是這個web開發者的新手事宜。我已經使用Ajax(JQuery lib)創建了一個聊天框。如何使用AJAX發送數據到'post.php'? (沒有Jquery)
現在,我想嘗試做類似的事情,而不使用Jquery來理解Ajax是如何工作的。首先,我只想使用AJAX在log.html上編寫消息,然後我可以稍後閱讀它們。但我不明白爲什麼我不能發送我的textarea數據到post.php。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Teste</title>
<script type="text/javascript">
function sendXMLDoc(){
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");
}
var message=document.getElementById('msg').value;
xmlhttp.open("POST", "post.php", false);
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 0) {
alert("UNSENT");
}
if(xmlhttp.readyState == 1) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
xmlhttp.send(message);
}
</script>
xmlhttp.send(data):爲什麼我沒有發送我的數據到post.php?
post.php中是我寫我log.html(但我不能把我的消息,我不明白爲什麼):
<?php
$text = $_POST['message']; // WHY I CAN'T RECEIVE MY POSTED MESSAGE?
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".$text."<br>\n</div>\n");
fclose($fp);
?>
這是我form.html
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc();">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit" value="Send"/>
</form>
</body>
嘗試添加類似於'xmlhttp.setRequestHeader(「Content-Type」,「application/x-www-form-urlencoded」)的請求頭文件# –