I had read something like that in another question. Based on this tutorial: I found the answer to all my problems.
this tutorial explain how to use a PJAX library that manages both the client and server side.
Thanks to 3 rows of code you can obtain a speed navigation without reload the page.
- Install client side library from jQuery-pjax page
- into your html page that send the request add:
<a href='/yourLink' data-pjax='main'>YourLink</a>
where main
is the div that will content yout change. In my case is:
<div id="main" class="main">
{{{body}}}
</div>
In your.js file add $('a[data-pjax]').pjax();
This command 'simply call the pjax extension on every element that contains the data attribute ‘data-pjax’'
Install inside express the depency with the command: npm install --save express-pjax
Set your server:
var app = express();
var pjax = require('express-pjax');
...
app.use(pjax())
- Replace the normal rendering:
res.render('index', {title: "Index"});
with
res.renderPjax('index', {title: "Index"});
UPDATE
Alternatively you can obtain the same result. Consider that the structure of the project is as follows:
views
|-> partials
| |-> addtest.hbs
|
|-> index.hbs
For example, image that in your index.hbs you have a sidebar with different items, described in this way:
<li>
<a href="#testDB" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
<img src="../img/database-data.svg" class="svg icon">Test</a>
<ul class="collapse list-unstyled select-specific" id="testDB">
<li value="addTest" class=" ">
<a href="#" id="add-new-test">Add Test</a>
</li>
....
....
</ul>
</li>
Inside the partials directory you have a simply form.
Now for manage the form you have to do two operations:
Server side: For switching from one partial to another without refresh the page, you specify:
router.get('/addtest', function (req, res) {
res.status(200);
res.header("Content-Type", "text/html");
res.render('partials/addtest', {title: "Add Test"});
});
Client side: In your client side file, you add make a simple get request:
$('#add-new-test').click(function (event) {
$.get('/addtest').then(function (data) {
$('#main').html(data);
});
});
In this way, when you make a get request with the same address (i.e in this case /addtest) the client add a part of code inside your view without refresh all.
NOTE: Keep in mind that, if you needed a some file.js in your partial, for load the file, use this:
<script>
var url = "/scripts/script.js";
$.getScript(url);
</script>
This is used for avoid: “Synchronous XMLHttpRequest on the main thread is deprecated…”
because the call is asynchronous. For more info..
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…