如何将URL参数传递给AJAX并刷新URL并管理内容

时间:2016-12-01 13:28:05

标签: javascript jquery ajax

我有以下代码,这些代码不能很好地工作,并且想知道我做错了什么。有时候它不能在localhost下运行,有时我会在开头增加额外的斜线,这会增加数量。

如果有人能说得对,那就太好了。

的index.html

<html>
<head>
</head>
<body>
    <div>Main Body</div>
    <div>URL Params: <span class="body-value"></span></div>
    <div class="ajax"></div>

    <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function(){

            $('.body-value').text(window.location.search);

            var url_search = '?test=2';
            var r = /[^\/]*$/;
            var url_base = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + url_search;
            var url_ajax = (window.location.protocol + "//" + window.location.host + "/" + window.location.pathname).replace(r, '') + 'ajax.html' + url_search;

            //window.history.pushState(new Date(),'',url_base);
            $('.ajax').load(url_ajax);

        });
    </script>
</body>
</html>

ajax.html

<div>Ajax</div>
<div>URL Params: <span class="ajax-value"></span></div>

<a href="#" class="ajax-change" data-value="3">Change test to 3</a>
<a href="#" class="ajax-change" data-value="4">Change test to 4</a>

<script type="text/javascript">
    $(document).ready(function(){
        $('.ajax-value').text(this.location.search);

        $('.ajax-change').click(function(evt){
            evt.preventDefault();

            var numb = $(this).data('value');

            var url_search = '?test=' + numb;
            var r = /[^\/]*$/;
            var url_base = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + url_search;
            var url_ajax = (window.location.protocol + "//" + window.location.host + "/" + window.location.pathname).replace(r, '') + 'ajax.html' + url_search;

            window.history.pushState(new Date(),'',url_base);
            $('.ajax').load(url_ajax);

        })

    });
</script>

感谢您的帮助

0 个答案:

没有答案