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

使用JavaScript+Node.js+Express修改输入框时浏览器提示无法加载/undefined

问题排查与修复方案

核心问题分析

你遇到的页面跳转、AJAX回调不触发问题,主要由几个代码细节错误导致:

  1. XMLHttpRequest创建语法错误
    newXMLHttpRequest() 缺少空格,应为 new XMLHttpRequest(),这会直接导致无法创建请求对象,代码进入catch块但未处理后续默认行为,引发页面跳转。

  2. 未阻止表单默认提交行为
    如果下拉框在<form>标签内,onchange事件会触发表单默认提交,直接覆盖AJAX逻辑,导致页面跳转至默认路径(未设置action时会出现/undefined的404)。

  3. Node.js错误处理语法错误
    res.status = 500 是错误写法,Express中status是方法,需改为res.status(500)。

  4. 冗余数组语法
    [asset = e.value] 里的赋值表达式无意义,直接用[e.value]即可,避免不必要的变量混淆。


修正后的代码片段

前端updateLocation函数
function updateLocation(e){
  // 阻止表单默认提交行为,避免页面跳转
  e.preventDefault();
  getRecord([e.value], 'get', '/assetLocation', function (location) {
    console.log(location)
  })
}
前端getRecord函数
//request records from database
function getRecord(data, queryType, id, callback){
  try{
    const encodedData = encodeURIComponent(JSON.stringify(data));
    // 修正XMLHttpRequest创建的空格问题
    const xhttp = new XMLHttpRequest();
    xhttp.open(queryType, `${id}?data=${encodedData}`);
    xhttp.onload = function(){
      if (this.status == 200){
        callback(JSON.parse(this.responseText))
      }else{
        errorParser(this)
      }
    }
    // 新增错误监听,方便排查请求失败情况
    xhttp.onerror = function() {
      console.error('AJAX请求发生错误');
    }
    xhttp.send();
  } catch (err){
    console.log(err)
  }
}
Node.js路由代码
app.get("/assetLocation", (req, res) => {
  try{
    const assetName = JSON.parse(req.query.data)[0];
    res.status(200).send(JSON.stringify({'test':'test'}))
  } catch (err) {
    // 修正status方法的调用方式
    res.status(500);
    sendResponse(res, err);
  }
});
补充:下拉框事件绑定

确保HTML中正确传递事件对象:

<select onchange="updateLocation(event)">
  <!-- 选项内容 -->
</select>

现象解释

  • 偶尔能收到响应但仍跳转:是因为少数情况下代码侥幸执行完成,但表单默认提交的跳转逻辑随后触发,覆盖了AJAX回调的效果。
  • 提前跳转:是XMLHttpRequest创建失败后,未阻止默认行为,浏览器直接执行表单提交。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:27:21