天天看点

js怎么实现ajax请求,js实现ajax请求

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中

提交

get