function Ajax(type, url, data, success, failed){
// 创建ajax对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
var type = type.toUpperCase();
// 用于清除缓存
var random = Math.random();
if(typeof data == 'object'){
var str = '';
for(var key in data){
str += key+'='+data[key]+'&';
}
data = str.replace(/&$/, '');
}
if(type == 'GET'){
if(data){
xhr.open('GET', url + '?' + data, true);
} else {
xhr.open('GET', url + '?t=' + random, true);
}
xhr.send();
} else if(type == 'POST'){
xhr.open('POST', url, true);
// 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
// 处理返回数据
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
success(xhr.responseText);
} else {
if(failed){
failed(xhr.status);
}
}
}
}
}
/*******************************
* Description:微信分享通用代码
* 使用方法:_WXShare('分享显示的LOGO','LOGO宽度','LOGO高度','分享标题','分享描述','分享链接','微信APPID(一般不用填)');
*******************************/
function _WXShare(img,width,height,title,desc,url,appid){
//初始化参数
img=img||'http://a.zhixun.in/plug/img/ico-share.png';
width=width||100;
height=height||100;
title=title||document.title;
desc=desc||document.title;
url=url||document.location.href;
appid=appid||'';
//微信内置方法
function _ShareFriend() {
WeixinJSBridge.invoke('sendAppMessage',{
'appid': appid,
'img_url': img,
'img_width': width,
'img_height': height,
'link': url,
'desc': desc,
'title': title
}, function(res){
_report('send_msg', res.err_msg);
})
}
function _ShareTL() {
WeixinJSBridge.invoke('shareTimeline',{
'img_url': img,
'img_width': width,
'img_height': height,
'link': url,
'desc': desc,
'title': desc
}, function(res) {
_report('timeline', res.err_msg);
});
}
function _ShareWB() {
WeixinJSBridge.invoke('shareWeibo',{
'content': desc,
'url': url,
}, function(res) {
_report('weibo', res.err_msg);
});
}
// 当微信内置浏览器初始化后会触发WeixinJSBridgeReady事件。
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
// 发送给好友
WeixinJSBridge.on('menu:share:appmessage', function(argv){
_ShareFriend();
});
// 分享到朋友圈
WeixinJSBridge.on('menu:share:timeline', function(argv){
_ShareTL();
});
// 分享到微博
WeixinJSBridge.on('menu:share:weibo', function(argv){
_ShareWB();
});
}, false);
}
javascript ajax请求封装和微信分享通用代码
最新推荐文章于 2024-12-08 20:47:17 发布