<script>
function xmlAjax(opt) {
return new Promise(function (resolve, reject) {
var initOpt = {
method: 'post'.url: ' '.data: null.async: true.// Tell the server what data I am giving you
contentType: 'application/json; charset=UTF-8'.done: function () {},
fail: function () {}};var endobj = Object.assign({}, initOpt, opt);
//1. Create XML objects
var xhr = new XMLHttpRequest();
var isGet = endobj.method.toLowerCase() == 'get';
if (isGet && endobj.data) {
var str = ' ';
for (var key in endobj.data) {
str += key + '=' + endobj.data[key] + '&';
}
str = str.substring(0, str.length - 1);
endobj.url = endobj.url + '? ' + str;
}
//2. Create an HTTP request and link to the server
xhr.open(endobj.method, endobj.url, endobj.async);
//3. The request header must be between open and send
xhr.setRequestHeader('Content-Type', endobj.contentType);
//4. Send data
if (isGet) {
xhr.send(null);
} else {
if (endobj.data) {
var dataparam = JSON.stringify(endobj.data);
xhr.send(dataparam);
} else {
xhr.send(null);
}
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
// endObj.done(data);
resolve(data)
} else {
reject('error')
switch (xhr.status) {
case 500:
break;
case 400:
break;
case 304:
break;
}
endObj.fail('error');
}
}
}
})
}
xmlAjax({
url: 'http://localhost:3000/msg/list'.type: 'post'.data: {
name: 'laney'.age: '30'
}
}).then((res) = > {
if (res.result.focus) {
return xmlAjax({
url: 'http://localhost:3000/msg/list/hello'.type: 'post'.data: {
name: 'laney'
}
})
}
}).then(function (res) {
console.log(res);
})
</script>
Copy the code