- 封装
var ajax = {
getxhr: function() {
return new XMLHttpRequest();
},
get: function(url, fun, sync=true) {
var xhr = this.getxhr();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
fun(xhr.responseText);
}
}
xhr.open('get', url, sync);
xhr.send();
},
post: function(url, data, fun, sync=true) {
var xhr = this.getxhr();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
fun(xhr.responseText);
}
}
xhr.open('post', url, sync);
xhr.send(data);
}
}
- 使用
document.getElementById('id').onclick = function() {
ajax.get('127.0.0.1:8000/gets', true, function(data) {
alert(data);
);
};