为给网站添加小功能,需要获取服务器端动态内容,不想引入相对庞大的Jquery或其他js。所以,使用原生javascript实现ajax,做一个记录以便重复使用。代码如下:
function doGet(url, str) {
let xhr = new XMLHttpRequest();
if (str == '') {
xhr.open('get', url);
} else {
xhr.open('get', url + '?' + str);
}
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
return xhr.response;
}
}
}
}
function doPost(url, str) {
let xhr = new XMLHttpRequest();
xhr.open('post', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(str);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
return xhr.responseText;
}
}
}
}
代码简单,未加注释,一看就懂。