如何从XMLHttpRequest返回的JSON中提取url、title、img等字段的值?
问题排查
- 事件监听逻辑冲突:你在
onreadystatechange的判断分支里才注册onload回调,当readyState变为4的时候请求已经完成,此时注册的onload永远不会触发,Promise无法进入resolved状态,后续链式调用的then不会执行 then链传值中断:第一个then的回调执行console.log(data)后没有返回data,第二个then接收的参数是undefined,animepost函数自然无法读取对应字段- 错误处理逻辑异常:请求状态码非200时直接调用
testjs()重试,没有reject当前Promise,会导致大量pending的Promise堆积,且无重试上限容易陷入死循环 - 参数拼写错误:
sendRequest的第一个形参meyhod为拼写错误(应为method),虽当前逻辑未用到该参数,但属于潜在问题 - 随机ID命中率低:你生成的随机ID范围过大,很多ID不存在对应动画资源,会频繁触发404错误
修复后的实现代码
const base_url = "https://api.jikan.moe/v3" // 增加重试上限避免死循环 const MAX_RETRY = 10 let retryCount = 0 function random(){ // 缩小ID范围提高有效资源命中率 return Math.floor(Math.random() * 30000); } function sendRequest(method, base_url){ return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); const id = random(); request.open('GET', `${base_url}/anime/${id}`); request.responseType = 'json' // 统一用onload处理请求完成逻辑 request.onload = () => { if (request.status === 200) { retryCount = 0 resolve(request.response) } else { reject(request.status) } } request.onerror = () => reject(request.statusText) request.send(); }) } function testjs(){ sendRequest('GET', base_url) .then(data => { console.log('接口返回完整数据:', data) return data // 传递数据给下一个then回调 }) .then(animepost) .catch(err => { console.log('请求失败,重试中,错误信息:', err) if(retryCount < MAX_RETRY){ retryCount++ testjs() }else{ console.log('超过最大重试次数,请稍后再试') retryCount = 0 } }) } function animepost(data){ console.log('提取到的图片地址:', data.image_url) console.log('提取到的标题:', data.title) console.log('提取到的详情页地址:', data.url) } // 执行调用 testjs()
内容的提问来源于stack exchange,提问作者LazyShagyDude
相关产品推荐
相关产品推荐

