GET是最常见的请求类型。对于XHR而言,位于传入open()方法的URL末尾的查询字符串必须经过正确编码,addURLParam()函数可以辅助向现有的URL末尾添加查询字符串参数:
function addURLParams(url,name,value){
url += url.indexOf("?")==-1?"?":"&";
url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
return url;
}
POST请求通常用于向服务器发送应被保存的数据。POST请求应该吧数据作为请求的主体提交(主体可以包含非常多的数据且格式不限)。
xhr.open("post","example.php",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var form = document.getElementById("formA");
xhr.send(serialize(form));