1.发送GET
var httpRequest = new XMLHttpRequest(); //第一步:建立所需的对象
httpRequest.open('GET', '/MsgShow?', true); //第二步:打开连接 将请求参数写在url中 ps:"./Ptest.php?name=test&nameone=testone"
httpRequest.send(); //第三步:发送请求 将请求参数写在URL中
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
console.log(httpRequest.responseText);
}
};
2.发送POST
var xhr = new XMLHttpRequest();
var data = Math.round(new Date().getTime() / 100);
var body= "msg="+encodeURIComponent("你好");
xhr.open("POST", "/Msg" , true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(body);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) { //证明服务器已经准备就绪
if (xhr.status == 200) { //页面请求成功
var txt = xhr.responseText; //表示取出数据
console.log(txt);
}
}
}
网友评论