Permalink
Browse files

Added a 'fragment' option to support servers that always return full …

…HTML pages

The 'fragment' option allows specifying a string selector which selects an element to be pulled out of the received response HTML. This is useful if you have no influence on the server side or do not want to modify the backend application. For example, 'fragment: "#content"' pulls the content element out of the response and inserts its children into the container element that you chose.
  • Loading branch information...
1 parent a19d6fe commit 124daed4772473e7bd0960b5321087cbb4cbff69 Markus Kaiserswerth committed with defunkt Jul 7, 2011
Showing with 22 additions and 5 deletions.
  1. +4 −0 README.md
  2. +18 −5 jquery.pjax.js
View
@@ -96,6 +96,10 @@ following additions:
* `timeout` - pjax sets this low, <1s. Set this higher if using a
custom error handler. It's ms, so something like
`timeout: 2000`
+* `fragment` - A String selector that specifies a sub-element to
+ be pulled out of the response HTML and inserted
+ into the `container`. Useful if the server always returns
+ full HTML pages.
## $.pjax( options )
View
@@ -45,7 +45,8 @@ $.fn.pjax = function( container, options ) {
var defaults = {
url: this.href,
container: $(this).attr('data-pjax'),
- clickedElement: $(this)
+ clickedElement: $(this),
+ fragment: null
}
$.pjax($.extend({}, defaults, options))
@@ -107,10 +108,20 @@ $.pjax = function( options ) {
$container.trigger('end.pjax')
},
success: function(data){
- // If we got no data or an entire web page, go directly
- // to the page and let normal error handling happen.
- if ( !$.trim(data) || /<html/i.test(data) )
- return window.location = options.url
+ if ( options.fragment ) {
+ // If they specified a fragment, look for it in the response
+ // and pull it out.
+ var $fragment = $(data).find(options.fragment)
+ if ( $fragment.length )
+ data = $fragment.children()
+ else
+ return window.location = options.url
+ } else {
+ // If we got no data or an entire web page, go directly
+ // to the page and let normal error handling happen.
+ if ( !$.trim(data) || /<html/i.test(data) )
+ return window.location = options.url
+ }
// Make it happen.
$container.html(data)
@@ -123,6 +134,7 @@ $.pjax = function( options ) {
var state = {
pjax: options.container,
+ fragment: options.fragment,
timeout: options.timeout
}
@@ -202,6 +214,7 @@ $(window).bind('popstate', function(event){
if ( $(container+'').length )
$.pjax({
url: state.url || location.href,
+ fragment: state.fragment,
container: container,
push: false,
timeout: state.timeout

0 comments on commit 124daed

Please sign in to comment.