JavaScript重定向时如何传递含@符号的邮箱URL参数?
解决JavaScript重定向传递邮箱地址作为URL参数的问题
问题出在未对邮箱地址中的特殊字符做URL编码。URL里的@、&等字符属于特殊符号,直接拼接会被浏览器解析为URL结构的一部分,导致参数传递失效。
解决方案
使用JavaScript的encodeURIComponent()函数对邮箱地址进行编码,它会把所有非URL安全的字符转换为百分号编码格式,同时需要阻止表单的默认提交行为,避免干扰重定向逻辑。
修改后的代码
<form> <input type="email" id="mail" placeholder="YOUR EMAIL ADDRESS" required/> <input type="submit" value="SEND US THE LIST" onclick="return redirect();"/> <script> function redirect(event){ // 阻止表单默认提交动作 event?.preventDefault(); var email = document.getElementById("mail").value; // 对邮箱地址做URL编码 var encodedEmail = encodeURIComponent(email); window.location.replace(`https://rinateithan.com/thank-you?sender=${encodedEmail}`); return false; } </script> </form>
关键说明
encodeURIComponent(email)会将test@gmail.com编码为test%40gmail.com,确保邮箱地址能作为完整的参数被URL正确识别。event.preventDefault()和return false是为了避免表单默认提交导致的页面刷新,保证重定向逻辑正常执行。
内容的提问来源于stack exchange,提问作者Yotam Dahan
相关产品推荐
相关产品推荐

