js 发送 get 和 post 请求
借助 XMLHttpRequest 对象
1、新建对象
2、建立连接
3、发送请求
4、查看请求状态,接收返回数据
发送 get 请求:
var xhr = new XMLHttpRequest();//第一步:新建对象
xhr.open('GET', 'url', true);//第二步:打开连接 将请求参数写在url中
xhr.send();//第三步:发送请求 将请求参数写在URL中
/**
* 获取数据后的处理程序
*/
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var res = xhr.responseText;//获取到json字符串,解析
}
};
发送 post 请求:
var xhr = new XMLHttpRequest();//第一步:新建对象
xhr.open('POST', 'url', true); //第二步:打开连接
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
xhr.send('name=teswe&ee=ef');//发送请求 将情头体写在send中
/**
* 获取数据后的处理程序
*/
xhr.onreadystatechange = function () {//请求后的回调接口,可将请求成功后的逻辑
if (xhr.readyState == 4 && xhr.status == 200) {//验证请求是否发送成功
var res = xhr.responseText;//获取到服务端返回的数据
}
};
post 请求发送 json 数据:
var xhr = new XMLHttpRequest();//第一步:新建对象
xhr.open('POST', 'url', true); // 建立连接
xhr.setRequestHeader("Content-type","application/json");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
var obj = { name: 'zhansgan', age: 18 };
xhr.send(JSON.stringify(obj));//发送请求 将json写入send中
/**
* 获取数据后的处理程序
*/
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 代码逻辑
}
};

浙公网安备 33010602011771号