[英]Replace the URL, contents and title without reloading the page
我想通過更改div內容來創建一個頁面站點,而無需加載新頁面。 因此,我實現了這樣的代碼:
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>
腳本
$(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();
});
});
是否可以僅創建一個ajax調用並獲取返回的數據title和post數據。 單擊錨鏈接后,如何將瀏覽器地址更改為post / post_id 。
如果您只想進行一個ajax調用,這是一個好主意,則還需要更改服務器上的代碼。
它應該響應一個json對象:
json_encode( array( "title" => $title, "post_data" => $post_data ) );
您的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.