You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Vanilla JS发起AJAX请求并处理返回结果?代码调试求助

你的代码问题分析与修复

控制台日志为空的核心原因:AJAX是异步操作,你在调用open()后立刻console.log(httpRequest.responseText),此时请求还没完成,服务器还没返回数据,所以结果为空。必须等请求完成后,在onload事件里才能拿到响应。

下面是修复并优化后的代码:

(function () {
    function contentLoaded () {
        window.addEventListener('keyup', function (e) {
            // 用e.key代替keyCode(keyCode已废弃,兼容性更好)
            if (e.key === 'Enter') {
                const isbnInput = document.getElementById('isbn');
                if(isbnInput){
                    // 去掉输入首尾空格,避免无效请求
                    const item = isbnInput.value.trim();
                    if(item !== ''){
                        if(window.location.href.includes('/account/create')){
                            const httpRequest = new XMLHttpRequest();
                            // 用window.location.origin自动拼接协议、主机和端口,避免手动拼串出错
                            const apiUrl = new URL(`/book/search/${item}`, window.location.origin);
                            
                            httpRequest.open('GET', apiUrl.href);
                            // 设置响应类型为JSON,自动解析返回数据
                            httpRequest.responseType = 'json';
                            
                            // 请求成功完成后处理结果
                            httpRequest.onload = function() {
                                if (httpRequest.status >= 200 && httpRequest.status < 300) {
                                    // 这里能正常拿到服务器返回的数据
                                    console.log('获取到的图书数据:', httpRequest.response);
                                    // 示例:把数据展示到页面
                                    // document.getElementById('book-details').innerHTML = `<p>书名:${httpRequest.response.title}</p>`;
                                } else {
                                    console.error('请求失败,状态码:', httpRequest.status);
                                }
                            };
                            
                            // 处理网络错误情况
                            httpRequest.onerror = function() {
                                console.error('网络连接失败,请检查API地址或网络状态');
                            };
                            
                            // 发送请求(真正发起请求的步骤)
                            httpRequest.send();
                        }
                    }
                }
            }
        }, false);
    }
    window.addEventListener('DOMContentLoaded', contentLoaded, false);
}());

主要修改说明:

  • 异步结果处理:把console.log移到httpRequest.onload事件中,确保请求完成后再获取数据
  • 替换keyCode:用e.key === 'Enter'替代e.keyCode === 13,符合现代JS标准
  • URL优化:用new URL()和window.location.origin自动拼接地址,避免手动拼串出错
  • 输入校验:给item添加trim(),过滤空字符请求
  • 自动解析JSON:设置responseType = 'json',直接使用解析后的对象,无需手动JSON.parse
  • 错误处理:新增onerror事件处理网络错误,同时判断状态码处理服务器错误

现在运行修改后的代码,按Enter发起请求后,控制台就能正常显示服务器返回的JSON数据了!

内容的提问来源于stack exchange,提问作者Anirudh Lou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:16:09