URL未生成GET请求,无法通过XMLHttpRequest向ESP32提交数据
问题分析与修复方案
核心问题
- 未绑定按钮点击触发逻辑:你当前的XHR请求代码仅在页面加载时执行一次判断,但刚创建XHR对象时
readyState == 4的条件完全不满足,且没有给提交按钮绑定点击事件,导致点击按钮毫无反应。 - 错误的时机判断:
readyState == 4 && status == 200是用来判断请求完成且响应成功的回调条件,不是触发请求的前置条件,把请求代码放在这个判断里永远不会执行。
修复后的完整代码
<!DOCTYPE html> <html> <head> <title>Title of the document</title> </head> <body> Enter string <input id="text" type="text" name="input_string"> <input type="submit" value="Submit" id="test"> <script> // 获取提交按钮元素 const submitBtn = document.getElementById('test'); // 绑定点击事件 submitBtn.addEventListener('click', function(e) { // 阻止submit按钮默认的表单提交行为,避免页面刷新 e.preventDefault(); // 获取输入框的内容 const inputVal = document.getElementById('text').value; // 创建XHR对象 const xhttp = new XMLHttpRequest(); // 可选:监听请求完成事件,用于调试或处理响应 xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log('请求成功,响应内容:', this.responseText); } }; // 编码输入值,避免特殊字符破坏请求参数格式 const encodedVal = encodeURIComponent(inputVal); // 打开并发送GET请求 xhttp.open("GET", `http://192.168.43.154/get?input_string=${encodedVal}`, true); xhttp.send(); }); </script> </body> </html>
额外优化说明
- 用
encodeURIComponent()对输入值编码,防止输入包含空格、&等特殊字符导致请求参数异常。 - 添加了请求完成的回调逻辑,方便在控制台查看请求状态和响应内容,便于调试。
- 移除了无用的
hidden-formiframe,XHR提交无需依赖该元素。 - 使用
addEventListener绑定事件,比传统onclick更灵活,支持绑定多个事件处理函数。
内容的提问来源于stack exchange,提问作者ramesh adhikari
相关产品推荐
相关产品推荐

