//1 封装ajax
function ajax(option){
//创建异步对象
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//如果是get并且有数据
if(option.type=='get'&&option.data){
option.url=option.url+'?'+option.data;
}
//设置请求行
xhr.open(option.type,option.url);
//设置请求头(post有数据发送才需要设置请求头)
//判断是否有数据发送
if(option.type=='post'&&option.data){
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
}
//注册回调函数
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
//接收返回的数据类型
var type = xhr.getResponseHeader('Content-Type');
//json格式
if(type.indexOf('json')!=-1){
option.callback(JSON.parse(xhr.responseText));
}
//xml格式
else if(type.indexOf('xml')!=-1){
option.callback(xhr.responseXML);
}
//普通格式
else{
option.callback(xhr.responseText);
}
}
}
//发送请求主体
//判断不同的请求类型
xhr.send(option.type=='post'?option.data:null);
}
//2 调用实例
// 获取热词
function getHotWord () {
ajax({
type: 'get',
url: baseUrl + '/api/v1/search/hotword',
data: null,
callback: function (res){
var dat = [];
if (res.status == 1) {
console.log(res.data);
var hotword=res.data&&res.data.words[0];
if(hotword){
$input.setAttribute("data-hotword",hotword);
if(!$input.value){
let hword = res.data.words[0];
$input.value = hword;
let classAtr = $input.getAttribute("class");
let newClass = classAtr.concat(" hot-keyword");
$input.setAttribute("class",newClass);
}
}
}
}
})
}
//3调用方法
getHotWord ();