The Application
In PHP, I will output some initial views so web crawlers can scrape my site:
----------------
| cool view 1 |
----------------
| cool view 2 |
----------------
| cool view 3 |
----------------
| Load more |
----------------
Javascript also needs to dynamically generate the same views. When a user hits the “load more” button, it does an AJAX to the server and attaches the result to the page:
----------------
| cool view 1 |
----------------
| cool view 2 |
----------------
| cool view 3 |
----------------
| cool view 4 |
----------------
| cool view 5 |
----------------
| cool view 6 |
----------------
| Load more |
----------------
Current Implementation
Currently, my PHP views and JS views are written separately. Here’s an example of loading a hypothetical PHP view using the CodeIgniter framework.
view.php
<?php
<div>
<span>cool view</span>
<span><?=$id?></span>
</div>
?>
controller.php
$this->load->view(
'view',
array('id' => '999')
);
And here’s an example of the AJAX to load the hypothetical views with the Prototype framework.
ajax.php
echo json_encode(
array('id' => random())
);
view.js
MyView = Class.create({
initialize: function(id) {
var div = new Element('div');
var span0 = new Element('span').update('cool view');
var span1 = new Element('span').update(id);
div.appendChild(span0);
div.appendChild(span1);
return div;
}
});
controller.js
new Ajax.Request(
'/index.php/someController/someMethod', {
onSuccess: function(transport) {
var response = transport.responseText.evalJSON();
$('viewsContainer').appendChild(
new MyView(response.id)
)
}
}
);
Need a Cleaner Solution
I need a way to share the HTML template across PHP and JS without rewriting everything. In my actual project, I have dozens of views. Duplicating the view code in PHP and JS seems hard to maintain. I didn’t go with the cheap route of PHP printing out straight HTML to AJAX because 1) there’s extra size overhead to include the HTML tags, 2) it’s not client agnostic – that is, a non-browser client would not be able to understand the output, and 3) it doesn’t allow JS to cleanly attach listeners on subviews within the view.
you could serve the final html, directly to the browser:
the final parameter
falseloads the view into a variable, in this case returns it…then, on the javascript side, you would just create a new
div, and set it’sinnerHTMLto theresponse.text