AJAX中的POST与GET方式实例

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() + "&timestamp=" + 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图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值