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

如何在AJAX请求验证通过跳转后,为新页面对应字段填充数据

核心问题

跳转页面时原页面内存中的hold变量会随原页面上下文一起销毁,新页面是独立的运行环境,无法访问原页面的任何变量,因此填充字段的逻辑无法生效。

解决方案

方案1:localStorage存储(最适配当前场景)

localStorage是浏览器提供的同域名跨页面持久化存储API,适合存储非敏感的会话临时数据,修改代码如下:

登录页代码调整

function makeRequest() {
  // 补充变量声明,避免全局变量泄漏
  let httpRequest = new XMLHttpRequest();
  if (!httpRequest) {
    alert("Giving up :( Cannot create an XMLHTTP instance");
    return false;
  }
  httpRequest.onreadystatechange = displayContents;
  httpRequest.open("GET", queryUrl2, true);
  httpRequest.send();
}

function displayContents() {
  // 放开变量注释,避免校验时报未定义错误
  let email = $("#uname").val().trim();
  let password = $("#pword").val().trim();
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      let jsonResponse = JSON.parse(httpRequest.responseText);
      let verifyEmail = jsonResponse["email"];
      let verifyPhone = jsonResponse["phoneNumber"];
      if (email === verifyEmail && password === JSON.stringify(verifyPhone)) {
        // 删除原hold数组逻辑,将手机号存入localStorage
        const phone = JSON.stringify(jsonResponse["phoneNumber"]);
        localStorage.setItem("login_phone", phone);
        window.location.replace("../index.html");
      } else {
        alert(`Invalid Username and/or Password. Please confirm and try again.`);
        window.location.href = "/";
      }
    }
  }
}

makeRequest();
// 登录页原有window.onload逻辑完全删除,这部分逻辑需要迁移到新页面

新页面index.html补充逻辑

在index.html中引入jQuery后添加如下脚本:

$(document).ready(() => {
  // 读取localStorage存储的手机号
  const loginPhone = localStorage.getItem("login_phone");
  if (loginPhone) {
    setValue(loginPhone);
    // 填充完成后删除存储,避免后续打开页面重复填充旧数据
    localStorage.removeItem("login_phone");
  }
})

let setValue = (x) => {
  $("#sphone-1").text(x);
  $("#phone-1").val(x);
  $("#phone-2").focus();
};

方案2:URL参数传递

如果不需要持久化存储,也可以将参数拼接在跳转URL中,新页面从地址栏读取参数:

// 登录页跳转逻辑修改
const phone = encodeURIComponent(JSON.stringify(jsonResponse["phoneNumber"]));
window.location.replace(`../index.html?phone=${phone}`);

// 新页面读取参数逻辑
$(document).ready(() => {
  const params = new URLSearchParams(window.location.search);
  const loginPhone = params.get("phone");
  loginPhone && setValue(decodeURIComponent(loginPhone));
})

注意该方案参数会明文显示在地址栏,不要传递敏感数据。

方案3:sessionStorage存储

用法和localStorage完全一致,区别是sessionStorage会在浏览器标签页关闭后自动清空,适合存储单次会话的临时数据,安全性略高于localStorage。

额外优化点

  1. 不需要嵌套使用window.onload和$(window).ready,两者均为页面加载监听事件,保留任意一个即可
  2. 密码校验逻辑不要直接在前端明文对比,建议后端加密后返回校验结果,避免前端暴露校验规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:09:02