已向服务器发送请求,但XMLHttpRequest onload函数未触发,求排查
技术问题:XMLHttpRequest onload未触发但服务器已接收请求
已向服务器发送POST请求且服务器已接收,但XMLHttpRequest的onload函数完全未被调用,错误处理也无任何输出。该代码曾在Chrome扩展中正常运行,但在我的网站中无法生效,错误处理没有输出任何内容。(注:左侧为服务器接收内容,右侧为JS打印内容)
问题代码
alert("called") var Ttype = "" var Ttext = "" if(document.getElementById('blockArea').style.backgroundColor != ''){ Ttext = document.getElementById('linkArea').value; Ttype = "link"; }else{ Ttext = document.getElementById('blockArea').value; Ttype = "block"; } if(!(Ttext == "") && !(Ttext == null)){ var xhttp = new XMLHttpRequest(); xhttp.open('POST', 'http://127.0.0.1:5000', true); xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); console.log("send"); alert("xhttp") xhttp.send("data=*_website_*" + "*/*/" + encodeURIComponent(Ttype) + "*/*/" + xhttp.onload = function () { alert("onload") console.log("onload"); var response = xhttp.response; console.log("response"); setGlobalResponseVals(response, Ttext); setupTabs(); } xhttp.onerror = function () { console.error('Error:', xhttp.statusText); alert('Error: ' + xhttp.statusText); }; };
错误分析与修复方案
1. 语法错误:send方法参数未闭合
代码中xhttp.send的参数只写了一半就中断,导致后续的事件绑定代码根本无法执行。需要补全send的参数,比如原本要拼接Ttext的话,应该写成:
xhttp.send("data=*_website_*" + "*/*/" + encodeURIComponent(Ttype) + "*/*/" + encodeURIComponent(Ttext));
2. 事件监听绑定顺序错误
当前代码先调用xhttp.send(),再绑定onload和onerror回调。由于请求是异步的(第三个参数为true),send后请求可能立即完成,此时回调还未绑定,自然不会触发。正确顺序是先绑定事件监听,再调用send。
3. 潜在CORS问题(网站环境特有)
Chrome扩展拥有特殊权限,跨域请求不受普通网站的CORS规则限制。如果你的网站和服务器不同域,需要确保服务器配置了正确的CORS响应头(如Access-Control-Allow-Origin),否则请求会被浏览器拦截,也可能导致回调不触发。
修正后的代码示例
alert("called") var Ttype = "" var Ttext = "" const blockArea = document.getElementById('blockArea'); const linkArea = document.getElementById('linkArea'); if(blockArea.style.backgroundColor !== ''){ Ttext = linkArea.value; Ttype = "link"; }else{ Ttext = blockArea.value; Ttype = "block"; } if(Ttext && Ttext !== ""){ var xhttp = new XMLHttpRequest(); xhttp.open('POST', 'http://127.0.0.1:5000', true); xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 先绑定事件监听 xhttp.onload = function () { alert("onload") console.log("onload"); var response = xhttp.response; console.log("response"); setGlobalResponseVals(response, Ttext); setupTabs(); } xhttp.onerror = function () { console.error('Error:', xhttp.statusText); alert('Error: ' + xhttp.statusText); }; // 补全send参数,再发送请求 console.log("send"); alert("xhttp") xhttp.send("data=*_website_*" + "*/*/" + encodeURIComponent(Ttype) + "*/*/" + encodeURIComponent(Ttext)); }
内容的提问来源于stack exchange,提问作者Samit Manjunath
相关产品推荐
相关产品推荐

