最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing current page URL via hidden input field within form - Stack Overflow

programmeradmin2浏览0评论

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. I've tried using javascript:location.href, however it looks as though it'll pass that as a literal string.

<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. Any ideas here? Thanks in advance!

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. I've tried using javascript:location.href, however it looks as though it'll pass that as a literal string.

<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. Any ideas here? Thanks in advance!

Share Improve this question asked May 9, 2014 at 19:54 CodeMonkey13CodeMonkey13 1451 gold badge2 silver badges11 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

You can access the element in Javascript and change the value there

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

Example: http://jsfiddle/6zxD5/

I don't think it works that way. You could just use the onload callback to insert it when the page is pletely loaded:

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

If your document containing the form is already a PHP file , you can do

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

And in your html you would do

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

You can use JavaScript to set the value of the hidden field:

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

Example:

https://jsfiddle/moogs/mhjh0je3/

Since you also tagged PHP, here's the PHP version:

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

评论列表(0)

  1. 暂无评论