PHP+AJAX+POST DEMO[code]
以POST方式传值时,在服务端back.php接受数据时需要设置
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
否则,接收不到数据。另外还要注意一些编码的问题。
该demo由3个文件组成,前端index.html,ajax.js,服务端back.php
以下是完整代码:
index.html
<html> <head> <title>ajax post php</title> <script src="ajax.js" type="text/javascript"></script> </head> <body> <div style="color:red"; id="result"> here the content.. </div>
<form name="form1" id="form1" method="post" action="" onsubmit="send();return false;">
姓名:<input type="text" name="name" value="Linus"/><br/> 标题:<input type="text" name="title" value="Title "/><br/> 内容:<input type="text" name="content" value="Contentsssss"/><br/>
<input type="submit" name="postit" value="Do it"/> </form> </body> </html>
|
ajax.js
//ajax.js
function send(){
// instantiate XMLHttpRequest object
try { xhr = new XMLHttpRequest(); } catch (e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
// handle old browsers
if (xhr == null) { alert("Ajax not supported by your browser!"); return; }
//construct data
var name = document.form1.name.value; var title = document.form1.title.value; var content = document.form1.content.value; var sendData = "name="+escape(name)+"&title="+escape(title)+"&content="+escape(content); //sendData = encodeURI(sendData);
//alert(sendData);
var url = "back.php";
xhr.onreadystatechange = handle;
xhr.open("post",url,true); //xhr.setrequestheader("content-length",sendData.length);
xhr.setRequestHeader("cache-control","no-cache"); //without the line the back.php can not receive post data
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(sendData);
}
function handle(){ // only handle loaded requests
if(xhr.readyState ==4){ if(xhr.status == 200){ document.getElementById('result').innerHTML = xhr.responseText; }else{ alert("error occured"); }
}
} |
back.php
<?php
echo $_POST['name']." ---".$_POST['title']."---".$_POST['content']." "; //sleep(2);
?>
|
阅读(1904) | 评论(0) | 转发(0) |