话不多说,直接上代码,复制粘贴,把URL改成自己想访问的,即可使用
httpGetTest();
httpPostTest();
//get请求
function httpGetTest() {
var url = 'http://XXX/XXXApi';
console.log('start===>XMLHttpRequest');
var xhr = new XMLHttpRequest();
xhr.responseType = "text";
xhr.open('GET', url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;")
xhr.send();
xhr.onload = function(e) {
console.log('onload。e====>' + JSON.stringify(e));
};
xhr.onreadystatechange = function(e) {
console.log('onreadystatechange。e====>' + JSON.stringify(e));
if(xhr.readyState == 4 && xhr.status == 200){
var xhrRes = xhr.responseText;
console.log('return message====>' + xhrRes);
}
};
}
//post请求
function httpPostTest() {
var url = 'http://XXX/XXXApi?module=httpPostTest';
var xhr = new XMLHttpRequest();
xhr.responseType = "text";
xhr.open('POST', url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
//1. 发送 formData
var formData = new FormData();
formData.append("username", "Anne");
formData.append("accountnum", 123456);
xhr.send(formData);
//2. 发送 JSON
// xhr.send({"username": "Anne"});
//3. 发送 字符串
// xhr.send(JSON.stringify({"username": "Anne"}));
xhr.onload = function(e) {
console.log('httpPostTest onload。e====>' + JSON.stringify(e));
};
xhr.onreadystatechange = function(e) {
console.log('httpPostTest onreadystatechange。e====>' + JSON.stringify(e));
if(xhr.readyState == 4 && xhr.status == 200){
var xhrRes = xhr.responseText;
console.log('httpPostTest return message====>' + xhrRes);
//正常情况下收到返回值 {"status": 1, "res": "http post test return!"}
}
};
}