简体   繁体   English

通过表单中的隐藏输入字段传递当前页面的URL

[英]Passing current page URL via hidden input field within form

I'm trying to figure out how to pass the URL of a current page via a hidden field so that I can redirect back to that page after the form's input has been handled. 我试图弄清楚如何通过隐藏字段传递当前页面的URL,以便在处理完表单的输入后可以重定向回该页面。 I've tried using javascript:location.href, however it looks as though it'll pass that as a literal string. 我尝试使用javascript:location.href,但是看起来好像它将作为文字字符串传递。

<input type="url" id="location" name="location" value="javascript:location.href" hidden />

When viewing the page source, I can see that the value of this input box is "javascript:location.href" rather than the page's URL. 查看页面源代码时,我可以看到此输入框的值为“ javascript:location.href”,而不是页面的URL。 Any ideas here? 这里有什么想法吗? Thanks in advance! 提前致谢!

You can access the element in Javascript and change the value there 您可以访问Javascript中的元素并在那里更改值

document.getElementById('location').value = location.href;

Example: http://jsfiddle.net/6zxD5/ 示例: http//jsfiddle.net/6zxD5/

I don't think it works that way. 我认为这种方式不起作用。 You could just use the onload callback to insert it when the page is completely loaded: 您可以只在页面完全加载后使用onload回调将其插入:

<body onload="document.getElementById('location').value = document.location.href">

If your document containing the form is already a PHP file , you can do 如果包含表单的文档已经是一个PHP文件,则可以执行

 $yourPath = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

And in your html you would do 在你的HTML中,你会做

echo '<input type="url" id="location" name="location" value="'.$yourPath.'" hidden />';

You can use JavaScript to set the value of the hidden field: 您可以使用JavaScript设置隐藏字段的值:

document.getElementById('location').value = window.location.href;

Example: 例:

https://jsfiddle.net/moogs/mhjh0je3/ https://jsfiddle.net/moogs/mhjh0je3/

Since you also tagged PHP, here's the PHP version: 由于您还标记了PHP,因此以下是PHP版本:

<input type="hidden" id="location" name="location" value="<?php echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM