借助 XMLHttpRequest 对象
1、新建对象
2、建立连接
3、发送请求
4、查看请求状态,接收返回数据
发送 get 请求:
var xhr = new XMLHttpRequest();//第一步:新建对象
xhr.open(‘GET‘, ‘url‘, true);//第二步:打开连接 将请求参数写在url中
xhr.send();//第三步:发送请求 将请求参数写在URL中
/**
* 获取数据后的处理程序
*/
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var res = httpRequest.responseText;//获取到json字符串,解析
}
};
发送 post 请求:
var xhr = new XMLHttpRequest();//第一步:新建对象
xhr.open(‘POST‘, ‘url‘, true); //第二步:打开连接
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
httpRequest.send(‘name=teswe&ee=ef‘);//发送请求 将情头体写在send中
/**
* 获取数据后的处理程序
*/
xhr.onreadystatechange = function () {//请求后的回调接口,可将请求成功后的逻辑
if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
var res = httpRequest.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中
/**
* 获取数据后的处理程序
*/
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
}
};
原文:https://www.cnblogs.com/lk-food/p/12514913.html