js实现ajax请求,注意post和get 的区别
注意请求参数的区别
只写了成功的部分,异常的部分没有写
function ajaxFunc(method, url, async, data, callback) {
var xhr = null;
if (window.XMLHttpRequest) { //兼容写法
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
method = method.toLocaleUpperCase(); //将传入的参数都变成大写,避免下面判断失效
if (method == 'POST') {
xhr.open(method, url, async);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
} else if (method == 'GET') {
xhr.open(method, url + '?' + data, async); //get方式下将参数拼接到url后面
xhr.send();
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (callback) {
callback(xhr.responseText); // 回调函数处理返回的数据
} else {
alert(xhr.responseText)
}
}
}
}
}
post方式下参数直接在xhr.send中发送,在post方式下需要设置请求头xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
get方式下需要将参数拼接到url后面
实例应用方式如下:
两个实例:上面的是提交输入框的值
下面的是点击请求列表数据,并通过showList渲染到ul中
<input type="text" name="username" id="user"></input>
<input type="text" name="age" id="age"></input>
<button id="btn">提交</button>
<button id="btnList">get</button>
<ul id="ulList"></ul>
<script>
var oBtn = document.getElementById('btn');
var btnList = document.getElementById('btnList');
oBtn.onclick = function () {
var name = document.getElementById('user');
var age = document.getElementById('age');
var nameValue = name.value;
var ageValue = age.value;
data = 'username=' + nameValue + '&age=' + ageValue;
ajaxFunc('post', 'post.php', true, data)
}
btnList.onclick = function () {
ajaxFunc('get', 'getNews.php', true, '', showList)
}
function showList(data) {
var ulList = document.getElementById('ulList');
data = JSON.parse(data);
var str = '';
data.forEach(function (ele, index) {
str += '<li>' + ele.title + '--' + ele.date + '</li>';
})
ulList.innerHTML = str;
}
</script>