如何在跨PHP页面场景下将点击按钮的name值填充至联系表单subject输入框?
实现方案
跨页面传值直接用URL查询参数就能搞定,不需要额外引入第三方依赖,实现步骤如下:
修改index.php 按钮代码
给原有两个按钮绑定点击跳转逻辑,点击时把按钮自身的name属性值作为查询参数,拼接到contact.php的访问地址上:
<button name="contracted_instructor" onclick="location.href='contact.php?subject=' + encodeURIComponent(this.name)" > Contracted instructor </button> <button name="talented-people" onclick="location.href='contact.php?subject=' + encodeURIComponent(this.name)" > Talented people </button>
- 这里用
encodeURIComponent对参数值做编码,就算后续按钮name值包含中文、空格等特殊字符,也不会出现URL解析异常。
修改contact.php 表单输入框代码
替换原有subject输入框的代码,通过PHP读取URL传入的参数,动态设置输入框的默认值:
<input id="subject" type="text" name="subject" value="<?php echo isset($_GET['subject']) ? htmlspecialchars($_GET['subject']) : ''; ?>" >
- 用
$_GET['subject']读取URL携带的按钮name值 - 必须搭配
htmlspecialchars做内容转义,避免XSS安全漏洞 - 没有携带对应参数时,输入框默认为空,不影响正常表单提交逻辑
最终效果
点击index.php的任意按钮,页面跳转至contact.php时,URL会自动附带对应按钮的name值作为subject参数,contact.php加载完成后,subject输入框会直接填充对应的值,和需求预期完全一致。
内容的提问来源于stack exchange,提问作者Angry Progy
相关产品推荐
相关产品推荐

