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


Passing current page URL via hidden input field within form

我试图找出如何通过隐藏字段传递当前页面的URL,以便我可以在表单的输入处理后重定向到该页面。我试过使用javascript:location。Href,但是它看起来好像会把它作为一个字面值字符串传递。

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

在查看页面源代码时,我可以看到这个输入框的值是"javascript:location"。href",而不是页面的URL。有什么想法吗?提前感谢!

您可以在Javascript中访问该元素并更改其值

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

的例子:http://jsfiddle.net/6zxD5/

我不认为这是可行的。你可以使用onload回调函数在页面完全加载时插入它:

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

如果包含表单的文档已经是PHP文件,则可以执行

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

在你的html中你可以写

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

您可以使用JavaScript设置隐藏字段的值:

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

的例子:

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

由于您还标记了PHP,下面是PHP版本:

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