// url:请求地址
// data:发送服务器的请求
// callback:数据类型进行处理或者执行回调函数
// type:post还是get请求,默认为空则自动get
function ajax(url, data, callback, type) {
if(type == void(0)) type = "get";
var param = null;
if(data != null && typeof data == "object") {
param = obj2str(data);
if(type == "get") {
url += "?" + param;
param = null;
}
}
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open(type, url);
type == "post" && xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(param);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var html = xhr.responseText;
if(typeof callback == "function") {
callback(html);
}
}
};
}
//
// 将 JS 的 Object 类型对象转换为 & 符号连接参数列表字符串
// @param {object} object 比如:{a:1,b:2}
// @returns {string} 比如:a=1&b=2
//
function obj2str(object) {
var temp = [];
for(ns in object) {
var val = encodeURIComponent(object[ns]);
temp.push(ns + "=" + val);
}
return temp.join("&");
}
版权属于:kiss
本文链接:https://www.kiss69224.vip/archives/39.html
转载时须注明出处及本声明仅供学习交流,不做商业用途。(kiss-博出精彩)