Handling an AJAX response as a document?
-
12-06-2021 - |
Question
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?
Solution
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, whenexample.com/#!/somepage.php
is loaded and you handlesomepage.php
, requestsomepage.php?json
instead, and propagate the content of that request as appropriate.
This approach affords you a number of benefits.
- Reduced response size of the AJAX request
- Reduced server-side load, since no HTML need be rendered
- Avoids HTML parsing and some expensive DOM manipulation
- No dependence on browser to send appropriate AJAX-related headers
OTHER TIPS
Note that you don't actually need to use a regular expression to get the content from the returned data. With jQuery, for example, it's simply a matter of using the context
argument of the $ selector (live fiddle)
$.get("/", {}, function(data){
$("#text").append($("#login", data));
});
Also note that shebang navigation is often associated with some Javascript framework