在写简单几个活动页面时可能不想引入其它文件,这时候发送请求消息给后端,可以自己写原生方法,以下是参考代码:
// 原生ajax
var ajax = function() {};
ajax.prototype = {
request: function(method, url, callback, postVars) {
var xhr = this.createXhrObject();
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
(xhr.status === 200) ?
callback.success(xhr.responseText, xhr.responseXML) :
callback.failure(xhr,status);
};
if (method !== "POST") {
url += "?" + this.JSONStringify(postVars);
postVars = null;
} else {
postVars = this.JSONStringify(postVars);
}
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
xhr.send(postVars);
},
createXhrObject: function() {
var methods = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
],
i = 0,
len = methods.length;
for (; i < len; i++) {
try {
methods[i]();
} catch(e) {
continue;
}
this.createXhrObject = methods[i];
return methods[i]();
}
throw new Error("ajax created failure");
},
JSONStringify: function(obj) {
var str = '';
for(i in obj){
str += i+'='+obj[i]+'&'
}
return str.slice(0,-1);
}
};
// ajax完成后的处理函数
var callback = {};
callback.success = function(text, xml){
text = eval('('+text+')');
var html = '';
for (var i = 0; i < text.datas.ad.length; i++) {
html += '<li>'
html += ' <span class="ad-dot"></span>'
html += ' <a href="'+text.datas.ad[i].reurl+'" target="_blank">'+text.datas.ad[i].reurl_title+'</a>'
html += '</li>'
};
adText.innerHTML = html;
}
callback.failure = function(xhr, status){
alert('广告代码获取失败')
}
var ajax = new ajax();
ajax.request('POST', '<{$apiurl}>index.php?route=website/goods/textAdCover', callback, param)