一、使用XMLHttpRequest
主要分三步:
第一步:创建需要的对象,这里主要用到的是XMLHttpRequest,注意需要考虑早期的IE;
第二步:连接和发送;
第三步:接收;
二、发送post请求并处理
var httpRequest = new XMLHttpRequest();
httpRequest.open("POST",url,true);
httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
httpRequest.send("keyword="+keyword+"&name="+name);
httpRequest.onreadystatechange = ()=>{
if(httpRequest.readyState == 4 && httpRequest.status == 200){
var data = JSON.parse(httpRequest.responseText);
console.log(data);
}
}
发送Get请求并处理
var httpRequest = new XMLHttpRequest();//第一步:建立所需的对象
httpRequest.open('GET', 'url', true);//第二步:打开连接 将请求参数写在url中 ps:"./Ptest.php?name=test&nameone=testone"
httpRequest.send();//第三步:发送请求 将请求参数写在URL中
/**
* 获取数据后的处理程序
*/
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var json = httpRequest.responseText;//获取到json字符串,还需解析
console.log(json);
}
};