Handle XHR response error (#137)

* Move the XHR callback to a separate file
* Trigger an error event if the response cannot be parsed.
* Add tests for handle-response.js
This commit was merged in pull request #137.
This commit is contained in:
BehindTheMath
2018-03-15 16:12:32 -04:00
committed by GitHub
parent c1e5bf9c78
commit 2166866967
5 changed files with 310 additions and 65 deletions

View File

@@ -142,6 +142,8 @@ Pjax.prototype = {
doRequest: require("./lib/send-request.js"),
handleResponse: require("./lib/proto/handle-response.js"),
loadUrl: function(href, options) {
options = typeof options === "object" ?
extend({}, this.options, options) :
@@ -155,66 +157,7 @@ Pjax.prototype = {
trigger(document, "pjax:send", options)
// Do the request
this.request = this.doRequest(href, options, function(html, request) {
// Fail if unable to load HTML via AJAX
if (html === false) {
trigger(document, "pjax:complete pjax:error", options)
return
}
// push scroll position to history
var currentState = window.history.state || {}
window.history.replaceState({
url: currentState.url || window.location.href,
title: currentState.title || document.title,
uid: currentState.uid || newUid(),
scrollPos: [document.documentElement.scrollLeft || document.body.scrollLeft,
document.documentElement.scrollTop || document.body.scrollTop]
},
document.title, window.location)
var oldHref = href
if (request.responseURL) {
if (href !== request.responseURL) {
href = request.responseURL
}
}
else if (request.getResponseHeader("X-PJAX-URL")) {
href = request.getResponseHeader("X-PJAX-URL")
}
else if (request.getResponseHeader("X-XHR-Redirected-To")) {
href = request.getResponseHeader("X-XHR-Redirected-To")
}
// Add back the hash if it was removed
var a = document.createElement("a")
a.href = oldHref
var oldHash = a.hash
a.href = href
if (oldHash && !a.hash) {
a.hash = oldHash
href = a.href
}
this.state.href = href
this.state.options = clone(options)
try {
this.loadContent(html, options)
}
catch (e) {
if (!this.options.debug) {
if (console && console.error) {
console.error("Pjax switch fail: ", e)
}
return this.latestChance(href)
}
else {
throw e
}
}
}.bind(this))
this.request = this.doRequest(href, options, this.handleResponse.bind(this))
},
afterAllSwitches: function() {