Django中避免页面重定向:将/trail/1234改为/trail#1234的需求
无重定向实现密码验证后的作品集URL切换与图片加载
页面核心状态
- 密码输入前:展示模糊作品集主图
- 密码验证通过后:加载原图,同时URL从
/trail/1234变更为/trail#1234,全程无页面重定向
具体实现方案
1. 阻止默认表单提交(避免重定向)
监听密码提交表单的submit事件,调用preventDefault()阻止浏览器默认的页面跳转行为:
const passwordForm = document.getElementById('password-form'); passwordForm.addEventListener('submit', async (e) => { e.preventDefault(); // 阻止页面重定向 // 后续执行密码验证逻辑 });
2. 异步验证密码
通过AJAX异步请求后端接口验证密码,避免页面刷新:
const passwordInput = document.getElementById('password-input'); const submitBtn = document.getElementById('submit-btn'); submitBtn.addEventListener('click', async () => { const password = passwordInput.value; const response = await fetch('/api/verify-password', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ password }) }); const result = await response.json(); if (result.valid) { // 验证通过,执行URL修改和图片切换 updatePageState(); } else { alert('密码错误,请重试'); } });
3. 修改URL并切换图片
验证通过后,使用History API修改URL(无重定向),同时替换图片资源:
function updatePageState() { // 修改URL为/trail#1234 history.pushState({}, document.title, '/trail#1234'); // 切换为原图 const mainImg = document.querySelector('.portfolio-main-image'); mainImg.src = '原图资源地址'; // 移除模糊效果样式(如果通过CSS实现模糊) mainImg.classList.remove('blur-filter'); }
关键说明
- 使用
history.pushState()而非location.href,可以在不触发页面重定向的前提下修改浏览器地址栏URL - 图片切换直接操作DOM元素的
src属性,配合异步密码验证实现无刷新更新
内容的提问来源于stack exchange,提问作者Chandni
相关产品推荐
相关产品推荐

