执行AJAX请求后JS函数无法更新HTML文档的问题求助
解决AJAX异步请求后无法更新HTML的问题
Hey, I see the issue here—your AJAX request is asynchronous, which means when you try to return myData from getData() and assign it to innerHTML right away, the request hasn't finished yet. So you're just setting the HTML to an empty string (the initial value of myData).
Let's fix this by using a callback function (the most straightforward approach for your existing code) to update the DOM only after the AJAX request successfully retrieves the data.
修改后的JS代码
function getData(parameter, callback) { let xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // 当数据成功获取后,调用回调函数传递数据 callback(this.responseText); } }; xhttp.open("GET", "http://192.168.0.154/testing/getuser.php?q=" + parameter, true); xhttp.send(); } function showUser(str) { // 调用getData时传入回调函数,在回调里更新DOM getData(str, function(data) { document.getElementById("txt").innerHTML = data; console.log("Received data:", data); }); console.log("Selected value:", str); };
关键修改说明
- 移除了全局的
myData变量(全局变量容易导致意外问题,尽量避免) - 给
getData添加了第二个参数callback:这是一个函数,会在AJAX请求成功拿到数据后执行 - 在
showUser中,不再直接赋值innerHTML,而是通过回调函数确保我们只有在拿到数据后才更新页面
如果你更喜欢现代的异步写法,也可以用Promise配合async/await来实现,代码会更清晰且自带错误处理:
基于Promise的现代写法
function getData(parameter) { return new Promise((resolve, reject) => { let xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200) { resolve(this.responseText); } else { reject(new Error(`Request failed with status ${this.status}`)); } } }; xhttp.open("GET", "http://192.168.0.154/testing/getuser.php?q=" + parameter, true); xhttp.send(); }); } async function showUser(str) { console.log("Selected value:", str); try { const data = await getData(str); document.getElementById("txt").innerHTML = data; console.log("Received data:", data); } catch (error) { console.error("Error fetching data:", error); document.getElementById("txt").innerHTML = "Failed to load data."; } };
内容的提问来源于stack exchange,提问作者Velioc
相关产品推荐
相关产品推荐

