<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="d"></div>
<script type="text/javascript">
var $ = {
get: function (url, args, success, dataType) {
var xhr = this.createXhr();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = xhr.responseText;
if (dataType == 'json') {
data = JSON.parse(data);
}
success(data); //方法调用
}
}
//判断参数2如果是一个对象,就要调用parmas方法
if (typeof args == 'object') {
//调用parmas方法将对象转为字符串
args = this.parmas(args);
}
url = url + '?' + args;
xhr.open('get', url);
xhr.send();
},
createXhr: function () {
var xmlhttp = '';
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
return xmlhttp;
},
parmas: function (js) {
var str = '';
for (var key in js) {
str += key + '=' + js[key] + '&'; //id=1001&name=冰箱&
}
str = str.slice(0, str.length - 1);
return str;
},
post: function (url, args, success, dataType) {
var xhr = this.createXhr();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = xhr.responseText;
if (dataType == 'json') {
data = JSON.parse(data);
}
success(data);
}
}
xhr.open('post', url);
//判断args如果是对象,则需要转为字符串时
if (typeof args == 'object') {
args = this.parmas(args);
}
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(args);
},
ajax: function (obj) {
var url = obj.url;
var data = obj.data || {};
var type = obj.type || 'get';
var dataType = obj.dataType || 'text';
var success = obj.success;
if (type == 'get') {
this.get(url, data, success, dataType);
} else {
this.post(url, data, success, dataType);
}
}
};
$.ajax({
url: '2.php',
data: 'id=1&name=电视',
type: 'post',
dataType: 'json',
success: function (msg) {
document.getElementById('d').innerText = msg.id + msg.name;
}
});
/*$.post('2.php', {id:1001, name:"冰箱"}, function (msg) {
console.log(msg);
}, 'json');*/
//2.php?a=123&b=234
//{id:1001, name:"冰箱"} ==> id=1001&name=冰箱
//2.php?id=1001&name=冰箱
/*$.get('2.php', {id:1001, name:"冰箱"}, function (msg) {
//函数定义, 处理后端返回的数据
document.getElementById('d').innerText = msg;
console.log(msg);
}, 'json'); */
</script>
</body>
</html>
success自调用函数,把函数整体当实参使用,传给形参,