ajax实现代码
req
: 请求类型,GET或者POST
url
: 请求地址
func
: 实现请求后对返回数据的处理方法
body
:GET时为null,POST时为参数
function ajax(req, url, func, body)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
func(xmlhttp.responseText);
}
}
xmlhttp.open(req, url, true);
if (req == "POST") {
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}
xmlhttp.send(body);
}
在其他函数中使用ajax
function loadStory(id)
{
//console.log(id);
ajax("GET","/get/get_bj_content?id="+id, case_loadStory, null);
}
处理返回数据的方法函数。调用ajax函数需要对应的事件处理函数。
function case_loadStory(response){
if (response.length == 0) {
return false;
}
else {
var obj = JSON.parse(response);
//console.log(obj);
}
}
本文是对ajax封装的一次探索实践。