Skip to content

Instantly share code, notes, and snippets.

@qichunren
Created March 6, 2020 13:38
Show Gist options
  • Save qichunren/fe06c8c48c7b4ef1a90567dd993346ba to your computer and use it in GitHub Desktop.
Save qichunren/fe06c8c48c7b4ef1a90567dd993346ba to your computer and use it in GitHub Desktop.
Replace Rails Turbolinks with pjax
function pajx_request(url) {
Rails.ajax({
url: url,
type: "get",
success: function (data) {
console.log(data);
$("#pajx_container").html(data.documentElement.innerHTML);
window.history.pushState(null, null, url);
},
beforeSend: (xhr, options) => {
xhr.setRequestHeader('request-from', 'pajx');
return true;
},
error: function (data) { }
});
}
window.addEventListener("popstate", function(e) {
pajx_request(location.href)
});
document.addEventListener("DOMContentLoaded", function () {
$(".main-sidebar a").on("click", function (event) {
event.preventDefault();
let target_url = $(this).attr("href");
pajx_request(target_url);
});
});
....
<div id="pajx_container"><%= yield %></div>
.....
class ApplicationController < ActionController::Base
layout :set_app_layout
def set_app_layout
if request.headers["request-from"] == 'pajx'
false
else
'admin'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment