ajax.html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>GET VS. POST</title>
<script language="javascript">
var xmlHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject)
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
else if(window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
}
function createQueryString(){
var firstName = document.getElementByIdx_x_x_x_x_x("firstName").value;
var birthday = document.getElementByIdx_x_x_x_x_x("birthday").value;
var queryString = "firstName=" + firstName + "&birthday=" + birthday;
return encodeURI(encodeURI(queryString)); //两次编码解决中文乱码问题
}
function doRequestUsingGET(){
createXMLHttpRequest();
var queryString = "ajax.php?";
queryString += createQueryString() + "×tamp=" + new Date().getTime();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET",queryString);
xmlHttp.send(null);
}
function doRequestUsingPOST(){
createXMLHttpRequest();
var url = "ajax.php?timestamp=" + new Date().getTime();
var queryString = createQueryString();
xmlHttp.open("POST",url);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(queryString);
}
function handleStateChange(){
var responseDiv = document.getElementByIdx_x_x_x_x_x("serverResponse");
if(xmlHttp.readyState == 1){
responseDiv.innerHTML = "正在下载数据,请稍候<img src=loading.gif>";
}
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
responseDiv.innerHTML = decodeURI(xmlHttp.responseText); //解码
}
}
</script>
</head>
<body>
<h2>输入姓名和生日</h2>
<form>
<input type="text" id="firstName" /><br>
<input type="text" id="birthday" />
</form>
<form>
<input type="button" value="GET" οnclick="doRequestUsingGET();" /><br>
<input type="button" value="POST" οnclick="doRequestUsingPOST();" />
</form>
<div id="serverResponse"></div>
</body>
</html>
建立ajax.php文件
PHP代码:
<?php
if($_SERVER['REQUEST_METHOD']=="GET"){
sleep(5);
echo "通过GET方式提交".$_GET['firstName']."->".$_GET['birthday'];
}elseif($_SERVER['REQUEST_METHOD']=="POST"){
sleep(1);
echo "通过POST方式提交".$_POST['firstName']."->".$_POST['birthday'];
}
?>
将两文件放apache的目录下,打开路径访问即可。小提醒:直接打开hmtl是不会执行的,必须路径访问
loading图片