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

递归XHR函数onclick绑定异常:函数被直接调用而非绑定事件

解决递归点击绑定与JSON解析问题

咱们先梳理下你代码里的两个核心问题,再一步步修复:

问题1:点击事件被立即执行而非点击触发

你写的wordC.onclick=(function(i) {sendRequest(i);})(word);是立即执行函数(IIFE),这行代码运行时会立刻调用sendRequest(word),而不是把函数绑定到点击事件上。我们需要让它返回一个函数,这样点击时才会触发执行。

问题2:没有正确解析JSON响应

XHR返回的request.responseText是字符串格式,你直接用for (word in json)遍历的是字符串的每个字符,而非你期望的{"milk":1,...}里的键值对,必须先用JSON.parse()把字符串转成JSON对象。

修复后的完整代码

<!DOCTYPE html>
<html>
<head>
<title>Query Page</title>
<script type="text/javascript">
function inputReq(){ 
  sendRequest(wordform.word.value) 
}

function sendRequest(str){
  // 移除多余行
  const table = document.getElementById('table');
  while(table.rows.length > 2){ 
    table.deleteRow(2); 
  }

  const request = new XMLHttpRequest();
  console.log('sending request');
  request.open('GET', 'http://127.0.0.1:5000/api.html?query='+str, true);
  
  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      // 关键:把响应字符串解析为JSON对象
      const json = JSON.parse(request.responseText);
      console.log(json);

      // 遍历JSON对象的键值对
      for (const word in json){
        const row = table.insertRow();
        const scoreC = row.insertCell();
        const wordC = row.insertCell();
        
        scoreC.innerHTML = json[word];
        wordC.innerHTML = word;
        
        // 修复点击绑定:让IIFE返回一个函数,点击时才执行
        wordC.onclick = (function(i) {
          return function() {
            sendRequest(i);
          };
        })(word);
        
        // 可选:给可点击单词加样式,提示用户可交互
        wordC.style.cursor = 'pointer';
        wordC.style.color = 'blue';
      }
    } else {
      console.log("Silence on the line");
    }
  }
  request.send();
}
</script>
</head>
<body>
<h1>Query Page</h1>
<table id='table' style="width:100%">
  <tr>
    <form name='wordform'>
      <th>Concept: <input type="text" name="word"></th>
      <th><input type="button" onclick="inputReq()" value='Find Associations'></th>
    </form>
  </tr>
</table>
</body>
</html>

关键修改点说明

  • JSON解析:用JSON.parse(request.responseText)把响应字符串转成可操作的JSON对象,确保能正确遍历目标键值对。
  • 点击事件绑定:调整立即执行函数逻辑,让它返回一个新函数,这样每次循环都会捕获当前的word值,点击时才会调用sendRequest(i)。
  • 体验优化:给可点击单词加了指针光标和蓝色样式,让用户直观知道这是可交互元素(可选但实用)。
  • 变量规范:把table、request等变量改成const(无需重新赋值的场景),更符合现代JS编码规范。

这样修改后,点击表格里的单词就会触发新的sendRequest调用,实现递归展示关联结果的需求啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:58:02