function addURLParam(url, name, value){
url += (url.indexOf("?") == -1 ? "?" : "&");
url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
return url;
}
var url = "test.php";
//添加參數
url = addURLParam(url, "name", "Nicholas");
url = addURLParam(url, "hometown", "shanghai");
//初始化請求
xhr.open("get", url, false);
xhr.open("post", "test.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var form = document.getElementById("user");
//serialize()序列化表單數據
xhr.send(serialize(form));
<?php
//設置頭部信息,發送給服務器的數據出如今$_POST超級全局變量中。
//不然,要訪問一樣的數據,要用$HTTP_RAW_POST_DATA
header("Content-Type: text/plain");
echo <<<EOF
Name: {$_POST["username"]}
EOF;
?>