Skip to content

Commit

Permalink
Added a 'fragment' option to support servers that always return full …
Browse files Browse the repository at this point in the history
…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
Markus Kaiserswerth authored and defunkt committed Jul 7, 2011
1 parent a19d6fe commit 124daed
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 )
Expand Down
23 changes: 18 additions & 5 deletions jquery.pjax.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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)
Expand All @@ -123,6 +134,7 @@ $.pjax = function( options ) {

var state = {
pjax: options.container,
fragment: options.fragment,
timeout: options.timeout
}

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 124daed

Please sign in to comment.