Ajax (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。小型Ajax JavaScript库是专门为简化Ajax请求而设计的轻量级库。
原因:浏览器的同源策略限制 解决方案:
// 服务器端设置CORS头
// 或使用JSONP(仅限GET请求)
function jsonp(url, callback) {
const script = document.createElement('script');
const callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[callbackName] = function(data) {
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
document.body.appendChild(script);
}
原因:网络问题或服务器处理时间过长 解决方案:
// 设置超时时间
function fetchWithTimeout(url, options, timeout = 5000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timeout')), timeout)
)
]);
}
原因:用户频繁触发相同请求 解决方案:
// 请求防抖
function debounceFetch(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const debouncedFetch = debounceFetch(fetch, 300);
// 简易Ajax库实现
const miniAjax = {
get(url, options = {}) {
return this.request('GET', url, null, options);
},
post(url, data, options = {}) {
return this.request('POST', url, data, options);
},
request(method, url, data, options = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
// 设置请求头
if (options.headers) {
Object.keys(options.headers).forEach(key => {
xhr.setRequestHeader(key, options.headers[key]);
});
}
// 超时处理
if (options.timeout) {
xhr.timeout = options.timeout;
xhr.ontimeout = () => reject(new Error('Request timeout'));
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const response = options.responseType === 'json'
? JSON.parse(xhr.responseText)
: xhr.responseText;
resolve(response);
} catch (e) {
reject(e);
}
} else {
reject(new Error(`Request failed with status ${xhr.status}`));
}
};
xhr.onerror = () => reject(new Error('Network error'));
// 发送请求
if (data && typeof data === 'object') {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
} else {
xhr.send(data);
}
});
}
};
// 使用示例
miniAjax.get('https://api.example.com/data')
.then(data => console.log(data))
.catch(error => console.error(error));
小型Ajax库在简单项目中能提供高效的解决方案,但在复杂应用中可能需要考虑更全面的HTTP客户端库。
没有搜到相关的文章