封装ajax
Posted maps..xy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装ajax相关的知识,希望对你有一定的参考价值。
function format(obj) {
var temp = [];
for (var key in obj) {
temp.push(key + "=" + obj[key]);
}
return temp.join("&");
}
function extend() {
for (var i = 0; i < arguments.length; i++) {
for (var key in arguments[i]) {
arguments[0][key] = arguments[i][key];
}
}
return arguments[0];
}
function ajax(opt) {
var def = {
async: true,
method: ‘get‘,
data: null,
success: function() {}
}
var settings = extend({}, def, opt);
var data = typeof settings.data == ‘object‘ ? format(settings.data) : settings.data;
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
if (settings.method == ‘get‘) {
xhr.open(settings.method, settings.url + "?" + data, settings.async);
xhr.send();
} else if (settings.method == ‘post‘) {
xhr.open(settings.method, settings.url, settings.async);
xhr.setRequestHeader(‘Centent-Type‘, "application/x-www-form-urlencoded,charset-utf-8");
xhr.send(data);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var obj = JSON.parse(xhr.responseText);
settings.success(obj);
}
}
}
}
以上是关于封装ajax的主要内容,如果未能解决你的问题,请参考以下文章