I\'m looking for a clean way to do quite a trivial thing in JQuery Mobile.
When linking to an internal page to be loaded into the Dom, I want to read the query param
jQuery Mobile ignores (removes) querystring parameters in URL and shows URL with hash only. However, you can retrieve querystring only on pagecontainerbeforechange and when data.toPage
is a string not an object. At this stage, full URL is stored in data.absUrl
.
You may use $.mobile.path.parseUrl().search
method to retrieve querystring, or you can use .split("?")
, both should work properly.
$(document).on("pagecontainerbeforechange", function (e ,data) {
if (typeof data.toPage == "string") {
var url = $.mobile.path.parseUrl(data.absUrl),
querystring = url.search; /* retruns ?id=test1 */
/* or */
var url = data.absUrl,
querystring = url.split("?")[1]; /* retruns ?id=test1 */
}
});
Edit: If querystring comes after hash, $.mobile.path.parseUrl(url).search
will return no value as it considers it a hash. Hence, use second method .split("?")
.
Another possible way is to utilize pagecontainerbeforetransition
as it fires once and returns data.toPage
object and data.absUrl
string.
Custom function to process URL and retrieve querystring
function getParam(url) {
var parsed = $.mobile.path.parseUrl(url),
hash = parsed.hash.split("?");
return {
search: hash[1].split("=")[1]
};
}
Listen to pagecontainerbeforetransition
; both .toPage
and .absUrl
should be defined and .toPage
's ID is the page you want to utilize parameters at.
$(document).on("pagecontainerbeforetransition", function (e, data) {
if ($.type(data.toPage) !== "undefined" && $.type(data.absUrl) !== "undefined" && data.toPage[0].id == "pageID") {
var param = getParam(data.absUrl).search;
$(".selector", data.toPage).text("Retrieved: " + param);
}
});
Demo