首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript:解析URL中的参数,然后在URL中擦除它们

Javascript:解析URL中的参数,然后在URL中擦除它们
EN

Stack Overflow用户
提问于 2018-09-15 01:39:11
回答 1查看 47关注 0票数 0

我正在尝试预先填充一些字段,这些字段是作为参数对从URL传递的。拥有

www.example.com.com/myForm#myinput=123

作为href发送给最终用户,我将在打开链接后用"123“预填充表单域"myinput”。但是,用户还将在其浏览器中看到www.example.com.com/myForm#myInput=123。这就是为什么我要从他们的网址上删除"myInput=123“的原因。这样做的原因是,我不希望我的用户在填写表单时看到甚至更改URL中的值。

我试过了

history.pushState(null,'','/modifedURL')

HTML body中的"onload“或jquery中的"doc ready”。到目前为止,我尝试过,这只能在URL中没有任何参数的情况下独立工作,比如"www.example.com.com/myForm",但不能使用额外的注入参数。这是我到目前为止得到的代码的简化版本。注意,成功调用了modifyURL方法,但对URL没有影响:

<head>
    <meta charset="utf-8" />
</head>
<body onload="prefill();">
    Your Body Content

    <!-- Scripts at the bottom for improved performance. -->
    <!-- jQuery, required for all responsive plugins. -->
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


    <form  id="myForm"   method="POST">
        <input id="myinput" maxlength="50" name="myinput"  type="text"  />
        <br>
        <input type="submit" name="submit"   />
    </form>

    <script>        
        $(document).ready(function() {


            //do some code after html is loaded
        });

        /*
        window.onload = function () { 

        }        
        */   

        function prefill() {                               
            try{
                var currentURL = window.location.href;
                var n = currentURL.search("#");
                var sPageURL = currentURL.substring(n+1);   

                var urlVal = getURLVal(sPageURL);

                document.forms["myForm"]["myInput"].value = urlVal;

                //change URL is called, but cannot change the URL!
                modifyURL();


            } catch(e){
                alert("error " + e);  
                return false;
            }
            return true;

        }
        function modifyURL() {
            history.pushState(null, '', '/modifedURL'); 
            //even alert will fire, so pushState is skipped!!
            alert('URL modified');   
        }

        function getURLVal(query) {
            //parse parameter pair in url
        }                                       
    </script>
</body>

EN

回答 1

Stack Overflow用户

发布于 2018-09-15 01:51:26

你可以在你的HTML中直接包含数据,如果它总是相同的话。

有两种方法:

  1. <input id="myinput" maxlength="50" name="myinput" type="text" value="123" />

这实际上是将值放在输入field

  • <input id="myinput" maxlength="50" name="myinput" type="text" placeholder="123" />

这仅在用户插入任何实际值之前显示(在提交时,您不会获得任何值)

我希望这对你有用

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52336853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档