将用户重定向到已编码的网址 - 变量

时间:2017-07-09 17:19:52

标签: javascript html url

我目前正在处理一个URL,该URL对URL变量输入的URL进行编码。然后,用户将被重定向到http://example.net/?enc_url=THE ENCODED LINK

这是我以前的代码:

<!DOCTYPE html>
<html>
    <script type="text/javascript">
        setTimeout(function() {
            var uri = <?php echo $_GET["url"]; ?>
            var res = encodeURI(uri)
            location.href = 'http://example.com"/?enc_url={$res}'
        }
    </script>
</html>

请帮助我,但请记住,我还没有太多的PHP经验。谢谢你的帮助!

问候!

2 个答案:

答案 0 :(得分:0)

您正在尝试在Javascript中使用PHP语法。在Javascript中使用连接。

var res = encodeURIComponent(uri);
location.href = 'http://example.com/?enc_url=' + res;

您还错过了)来电的结束setTimeout()。你应该使用encodeURIComponent,而不是encodeURI;见Should I use encodeURI or encodeURIComponent for encoding URLs?

答案 1 :(得分:0)

只有PHP:

<?php
$enc_url = urlencode($_GET['url']);
header("Location: http://example.com/?enc_url=$enc_url");
?>

JavaScript的:

<!DOCTYPE html>
<html>
<script type="text/javascript">
setTimeout(function() {
    var uri = "<?php echo urlencode($_GET["url"]); ?>";
    location.href = `http://example.com/?enc_url=${uri}`;
}, 3000);
</script>
</html>