【问题标题】:How to change URL in JavaScript without storing in browser's history如何在不存储在浏览器历史记录中的情况下更改 JavaScript 中的 URL
【发布时间】:2018-02-13 12:48:55
【问题描述】:

我想在不影响浏览器历史记录的情况下更改 javascript 中的 URL。 我在

中有这个网址
http://abcd.com/parent/child/?id=xyz abc

这是一个 WordPress URL 我想要这个

http://abcd.com/newurl/xyz ABC

我在 javascript 中使用history.replaceState 函数来更改 URL,它工作正常,但是每当我从浏览器单击后退按钮或刷新页面时,它会将我从当前页面重定向到主页。

我想要的是,它应该存储原始 URL(http://abcd.com/parent/child/?id=xyz abc)并将这个 URL 显示给用户(http://abcd.com/newurl/xyz ABC

我只想更改 URL,而不是历史记录。 这是我的javascript代码

history.replaceState('', 'my title', 'http://abcd.com/newurl/<?php echo str_replace(" ","-",$_GET["id"]); ?>');

$_GET["id"] 是一个搅拌 xyz ABC

【问题讨论】:

    标签: javascript wordpress url browser-history


    【解决方案1】:

    这个怎么样?

    function changeUrl(title, url) {
        if (typeof (history.pushState) != "undefined") {
            var obj = {Page: title, Url: url};
            history.pushState(obj, obj.Page, obj.Url);
        }
    }
    

    【讨论】:

    • 它工作正常,但每当我点击后退按钮时,它只会显示旧 URL,但不会重定向我。但是当我第二次点击浏览器的后退按钮时,它会将我重定向到主页。有什么办法可以更改网址...?我从一个星期开始就解决了这个问题,但仍然面临这个问题。
    【解决方案2】:

    我认为你走错路了。您应该在 WordPress 中使用自定义重写规则来解决此问题,而不是在 JavaScript 中执行此操作。

    在这里阅读更多: http://codex.wordpress.org/Rewrite_API/add_rewrite_rule

    详细解决方案:

    例如,您希望网址 http://example.com/india/?id=vip/http://example.com/india/vip/

    其中indiapage slugid 是您的查询变量。

    将以下代码添加到您的functions.php 文件中:

    function add_query_vars($queryVars) {
        $queryVars[] = "id"; // represents the name of the string as shown in the URL
        return $queryVars;
    }
    
    // hook add_query_vars function into query_vars
    add_filter('query_vars', 'add_query_vars');
    
    function add_rewrite_rules($aRules) {
        $aNewRules = array('india/([^/]+)/?$' => 'index.php?pagename=india&id=$matches[1]');
        $aRules = $aNewRules + $aRules;
        return $aRules;
    }
    
    // hook add_rewrite_rules function into rewrite_rules_array
    add_filter('rewrite_rules_array', 'add_rewrite_rules');
    

    在你的代码中说page.php你可以使用像这样的变量

    if(isset($wp_query->query_vars['id'])) {
        $testid = urldecode($wp_query->query_vars['id']);
    }
    echo $testid;
    

    注意:请确保在更改上述内容后重置永久链接。

    【讨论】:

    猜你喜欢
    • 2014-01-23
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多