ajax的post請求

get和post是http請求方法最主要的兩種方式。php

post:html

來個例子test.html緩存

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<input type="password" id="password">
<input type="button" value="submit" id="submit">
<div id="txt"></div>
<script>
//監聽對象
document.getElementById('submit').onclick = function(){
  var password = document.getElementById('password').value;
  var url = "index.php?password=" + password;
  post(url,function(data){
    document.getElementById('txt').innerHTML = data;
  })
}
//簡單的post封裝
function post(url,callback,async){
  var xhr = new XMLHttpRequest();
  async = async ? async :true;
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      callback(xhr.responseText);
    }
  }
  xhr.open("post",param(url)[0],async);
  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
  xhr.send(param(url)[1]);
}
function param(url){
  var arr = url.split("?");
  return arr;
}
</script>
</body>
</html>

index.phpapp

<?php
  echo "your password is ".$_POST['password'];
?>

說明一下:post所請求的頁面是沒法使用緩存,跟get同樣的是,post這中請求方式通常也是採用異步。可是還有一個問題沒有搞明白,post傳遞的url中的字符串參數是否須要編碼?異步