I'm trying to implement AJAX with shebang - meaning that example.com/#!/somepage.php
is simply example.com/somepage.php
loaded into the content area of an AJAX site.
The obvious way of doing this is to just request somepage.php
and then replace the entire contents of the documentElement
with the new document. However that seems to kind of defeat the purpose of AJAX.
Instead, I'm thinking of trying to load somepage.php
, and then extracting the content
part of the page and simply put that in the content area.
To do this, I could use a regex to look for /<div id="content">.*</div>/
but that would be a very bad idea (the simplest problem being "which </div>
ends the content?). Instead, I'd like to be able to just do something like ajaxresponse.getElementById('content')
, but how would I go about converting ajaxresponse
to a document
(or documentFragment
) object?
Or is this just the wrong approach to implementing such an AJAX setup? Would I be better off having the server side check for X-Requested-With: XMLHttpRequest
and only send back the content area?
Instead of requesting the #!
'd page verbatim, request a variant that is compatible with your #!
handler.
This approach takes two steps.
Expose your content pages via JSON. Make this service available to requests that satisfy a particular condition, such as a special get parameter, extension, a header, etc. For example, /somepage.php?json
might serve the content of /somepage.php
in JSON.
Write your #!
handler so that when it handles a request, it calls upon the service you defined above for that page. For example, when example.com/#!/somepage.php
is loaded and you handle somepage.php
, request somepage.php?json
instead, and propagate the content of that request as appropriate.
This approach affords you a number of benefits.