首页 > 解决方案 > 当我在 url 处输入 ?variable=value 时如何更改值?

问题描述

情况:

  1. 输入值为空,类型为隐藏。
  2. 我在 url 输入 ?hiddenname=007
  3. 我单击按钮“提交”并导致函数调用()..

预计:

  1. 系统根据 ?hiddenname=007 在 url 使用函数 call() 将值填入输入
  2. 之后,系统将值为 007 的表单发送到服务器。

当前结果:

  1. 系统仍然发送空值的表单。

网址

localhost/index.html?hiddenname=007

索引.html

<!DOCTYPE html>
<html>
    <head>
        <script>
            function call(){
                document.forms["form1"].hiddenname.value=hiddenname;
                    console.log("function run");
                    }
        </script>
    </head>
    <body>
        <form name="form1" action="end.php">
            <input type="hidden" id="hiddenid" name="hiddenname" value="" />
              <input type="submit" id="send" onclick="call()"/>
            
        </form>
    </body>

结束.php

<?php
echo $_GET['hiddenname'];
?>

标签: javascriptformspostgethidden

解决方案


这将在窗口加载时hiddenname从 URL 查询字符串中获取值,然后设置hiddenid输入值:

window.onload = function () {

  // get the search params from the window's URL
  const urlParams = new URLSearchParams(window.location.search);

  // get the value of 'hiddenname'
  const myParam = urlParams.get('hiddenname');

  // store this value in the input with id="hiddenid"
  document.getElementById('hiddenid').value = myParam;
};

推荐阅读