GET请求使用setRequestHeader报错且XMLHttpRequest请求地址不符预期
修复你的请求问题 + 额外细节优化
先给你修正后的完整可行代码,之后我会拆解每个问题点:
function sendRequest(str) { var request = new XMLHttpRequest(); console.log('sending request'); request.onreadystatechange = function() { if (request.readyState === XMLHttpRequest.DONE) { // 处理响应:先解析JSON字符串为对象 let json; try { json = JSON.parse(request.responseText); } catch (err) { console.error('Failed to parse response:', err); return; } // 清空表格旧内容(可选,避免重复添加) while (table.firstChild) { table.removeChild(table.firstChild); } // 遍历JSON对象的键值对 for (const word in json) { if (json.hasOwnProperty(word)) { // 避免遍历原型链上的属性 const row = table.insertRow(); const scoreC = row.insertCell(); const wordC = row.insertCell(); scoreC.textContent = json[word]; wordC.textContent = word; } } } else { console.log("Silence on the line"); } }; // 移除GET请求不需要的Content-type头设置 request.open('GET', `http://127.0.0.1:5000/api.xml?query=${encodeURIComponent(str)}`, true); request.send(); }
关键问题修复说明
错误的请求头设置:
GET 请求不需要设置Content-type: application/x-www-form-urlencoded,这个请求头是用于 POST 请求发送表单数据时告知服务器数据格式的。你这里添加它不仅完全没用,还可能导致请求被异常处理,直接移除即可。请求地址不符合预期:
原代码里的URL写法本身逻辑是对的,但我做了两个优化:- 使用模板字符串让参数拼接更清晰易读;
- 用
encodeURIComponent()对str进行编码,避免当查询参数包含特殊字符(比如空格、&、=)时出现请求格式错误。
如果实际请求还是跳转到/?word=toast,你需要检查是否有其他代码在拦截/修改这个请求(比如全局的XMLHttpRequest拦截逻辑,或者页面上其他JS重写了请求地址)。
额外细节优化
concole.log拼写错误:修正为正确的console.log,不然这个状态日志永远无法正常输出。- JSON响应未解析:原代码直接把
responseText(字符串类型)当作JSON对象遍历,会导致遍历字符串的每个字符,用JSON.parse()解析后才能正确遍历键值对,同时加了try-catch处理解析失败的异常情况。 - 遍历对象时的安全检查:用
hasOwnProperty()确保只遍历对象自身的属性,避免遍历到原型链上的继承属性。 - 表格内容清空:添加了清空表格旧内容的逻辑,避免每次请求都往表格里追加重复数据。
- 用
textContent替代innerHTML:如果只是插入纯文本,textContent比innerHTML更安全,能避免潜在的XSS风险。
内容的提问来源于stack exchange,提问作者eddie
相关产品推荐
相关产品推荐

