简体   繁体   English

替换URL,内容和标题,而无需重新加载页面

[英]Replace the URL, contents and title without reloading the page

I want to create one page site by change div content with out load new page. 我想通过更改div内容来创建一个页面站点,而无需加载新页面。 So, I've implemented my code like this: 因此,我实现了这样的代码:

HTML: HTML:

<title>Post title</title>
<body>
    <a class="js-post-bt" href="/post/1" data-id="1"></a>
    <a class="js-post-bt" href="/post/2" data-id="2"></a>
    <a class="js-post-bt" href="/post/3" data-id="4"></a> 

    <div id="post-container"></div>
</body>

Script 脚本

$(function() {
    $(".js-post-bt").on("click", function(e) {
         var post_id = $(this).attr("data-id");
         $.ajax({
            url: "post_title.php?id="+post_id,
            success: function(data) {
                var title = data;
                $.ajax({
                    url: "post.php?id="+post_id,
                    success: function(data2) {
                        // how to change url to post/post_id?
                        document.title = title;
                        $("#post-container").html(data2);
                    }
                });
            }
        });

        e.preventDefault();
    });
});

Is it possible to create only one ajax call and get returned data either title and post data. 是否可以仅创建一个ajax调用并获取返回的数据title和post数据。 ANd how to change browser address to post/post_id after anchor link clicked. 单击锚链接后,如何将浏览器地址更改为post / post_id

If you want to make just one ajax call, which is a good idea, you will also need to change the code on your server. 如果您只想进行一个ajax调用,这是一个好主意,则还需要更改服务器上的代码。

It should respond a json object: 它应该响应一个json对象:

json_encode( array( "title" => $title, "post_data" => $post_data ) );

And you ajax call becomes: 您的ajax调用将变为:

$(function() {
    $(".js-post-bt").on("click", function(e) {
         var post_id = $(this).attr("data-id");
         $.ajax({
            url: "post_title.php?id="+post_id,
            dataType: "json",
            success: function(json_data){
                document.title = json_data["title"];
                $("#post-container").html(json_data["post_data"]);
            }
        });

        e.preventDefault();
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM