JavaScript中原生ajax的写法
function zheng(a) {
var headerSearechZheng = document.getElementById("header-search-zheng");
console.log(a.value);
var ajax = new XMLHttpRequest();
ajax.open("get", "shopping.json");
ajax.send();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
data = JSON.parse(data);
headerSearechZheng.innerHTML = "";
var result = [];
for (let i = 0; i < data.zheng.length; i++) {
if (data.zheng[i].shop.indexOf(a.value) != -1) {
// console.log(data.zheng[i].shop.indexOf(a.value));
// console.log(a.value.length);
var zhengBold = "";
zhengBold =
data.zheng[i].shop.slice(0, data.zheng[i].shop.indexOf(a.value)) +
"<strong>" +
data.zheng[i].shop.slice(
data.zheng[i].shop.indexOf(a.value),
data.zheng[i].shop.indexOf(a.value) + a.value.length
) +
"</strong>" +
data.zheng[i].shop.slice(
data.zheng[i].shop.indexOf(a.value) + a.value.length
);
// console.log(zhengBold);
result.push(zhengBold);
}
}
var str = "";
if (a.value == "") {
headerSearechZheng.innerHTML = "";
} else {
for (let i = 0; i < result.length; i++) {
str += "<li><a>" + result[i] + "</a></li>";
}
headerSearechZheng.innerHTML = str;
}
}
};
}
兼容IE的写法
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else { //IE6及其以下版本浏览器
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}