上一篇
"这需求也太急了吧!" 小张盯着产品经理刚发的消息直挠头,明天就要演示的H5页面,后端接口还没准备好,但静态数据已经发过来了——既有XML格式的配置表,又有JSON格式的产品数据,作为前端老司机,小张决定先通过本地数据模拟交互效果,等接口好了再无缝切换,下面这些方法,或许正是你需要的"救急锦囊"。
function loadXMLDoc(filename) { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { parseXML(this); // 解析XML的回调函数 } }; xhttp.open("GET", filename, true); xhttp.send(); } function parseXML(xml) { const xmlDoc = xml.responseXML; const items = xmlDoc.getElementsByTagName("item"); let output = ""; for (let i = 0; i < items.length; i++) { output += items[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = output; } // 使用示例 loadXMLDoc("config.xml");
function fetchXML(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'document'; xhr.onload = () => { if (xhr.status === 200) resolve(xhr.responseXML); else reject(new Error(`加载失败: ${xhr.statusText}`)); }; xhr.onerror = () => reject(new Error('网络错误')); xhr.send(); }); } // 使用示例 fetchXML('data/config.xml') .then(xmlDoc => { // 解析处理逻辑 }) .catch(console.error);
function getJSON(url, callback) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { try { const data = JSON.parse(xhr.responseText); callback(null, data); } catch (e) { callback(e); } } else { callback(new Error(xhr.statusText)); } } }; xhr.send(); } // 使用示例 getJSON('products.json', (err, data) => { if (err) return console.error('出错啦:', err); console.log('获取到的数据:', data); });
fetch('data/products.json') .then(response => { if (!response.ok) throw new Error('网络响应不正常'); return response.json(); }) .then(data => { console.log('数据加载成功:', data); // 这里处理数据 }) .catch(error => { console.error('请求出错:', error); });
// 注意:这种方式需要JSON文件放在public或可访问的静态资源目录 async function loadJSON() { try { const data = await import('./data/products.json', { assert: { type: 'json' } }); console.log('动态导入的数据:', data.default); } catch (e) { console.error('导入失败:', e); } }
路径问题:本地开发时建议使用绝对路径(如/data/config.xml
),避免相对路径导致的404
缓存处理:在开发阶段可以添加时间戳防止缓存
fetch(`data.json?t=${Date.now()}`)
错误处理:真实项目中一定要做好错误边界处理
function safeParseJSON(jsonString) { try { return JSON.parse(jsonString); } catch { return null; // 或者返回默认数据 } }
性能优化:大文件可以考虑分块加载或使用Web Worker解析
虽然JSON现在是主流,但在某些场景XML仍有优势:
建议新项目优先使用JSON,遇到特殊需求再考虑XML方案。
本地数据交互看似简单,但魔鬼藏在细节里,下次当你遇到"接口还没好,但我要先开发"的情况时,不妨试试这些方法,优秀的开发者不仅要会调接口,更要掌握各种mock数据的技巧,这样才能在前后端并行开发时游刃有余。
(注:文中代码在Chrome 94+、Firefox 90+等现代浏览器测试通过,2025年7月验证)
本文由 蒿金枝 于2025-07-31发表在【云服务器提供商】,文中图片由(蒿金枝)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/493739.html
发表评论