1、GET请求
GET最常用于向服务器查询信息。可在URL末尾添加查询字符串参数。
XHR中,传入open()方法的URL末尾的查询字符串必须经过正确的编码,使用encodeURIComponent()编码。所有名-值对儿必须由和号(&)分隔。
如:
xhr.open("get", "test.php?name1=value1&name2=value2", true);
向URL末尾添加查询字符串参数:
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);
2、POST请求
POST请求向服务器发送应该被保存的数据,把数据作为请求的主体提交。
POST请求的主体可包含非常多的数据,格式不限。
默认情况下,服务器对POST请求和提交Web表单的请求会做不同的处理。
也可使用XHR来模仿表单提交:
Content-Type头部信息设置为application/x-www-form-urlencoded
以适当的格式创建一个字符串
如:
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));
test.php代码:
<?php
//设置头部信息,发送给服务器的数据出现在$_POST超级全局变量中。
//否则,要访问同样的数据,要用$HTTP_RAW_POST_DATA
header("Content-Type: text/plain");
echo <<<EOF
Name: {$_POST["username"]}
EOF;
?>
注:POST消耗的资源比GET更多。发送相同量的数据,GET的速度最多可以比POST快一倍。