views:

28

answers:

2

I'm trying to reload a page with an appended variable in the URL, deviceID. It shows up in "realtime" div just fine. What am I doing wrong?:

document.getElementById("realtime").innerHTML = "<pre>"+JSON.stringify(msg)+"</pre>";

        var obj = jQuery.parseJSON(JSON.stringify(msg));
        var deviceId = obj.deviceId;

        var pathname = window.location.pathname;
        var pathAppend = pathname + "?deviceId=" + deviceId;

            window.location.reload(pathAppend);
A: 

The sample by Daniel has a bug -- the search string would get longer with each reload. A better way to do it would be:

// Gets all URL params
var urlParams = {};
(function () {
     var e,
          d = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); },
          q = window.location.search.substring(1),
          r = /([^&=]+)=?([^&]*)/g;

     while (e = r.exec(q))
         urlParams[d(e[1])] = d(e[2]);
})();

// Assigns the new value
var obj = jQuery.parseJSON(JSON.stringify(msg));
var deviceId = obj.deviceId;
urlParams['deviceId'] = deviceId;

// Gets the URL without params and anchors
var URL = window.location.href;
var searchAt = URL.indexOf(window.location.search);
if (searchAt > -1) {
    URL = URL.substr(0, searchAt);
}

// Constructs the new search string
var searchStr = "";
for (var i in urlParams) {
    searchStr += i + "=" + urlParams[i] + "&";
}

// Reloads the page
document.location.href = URL + "?" + searchStr;
Saul
A: 

It's because you're using window.location.reload incorrectly. reload accepts a boolean which:

when it is true, causes the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache. - MDC

You should do something like:

var query = window.location.search, deviceParam = "deviceId=" + deviceId;

//if there is a query string, append it, otherwise construct the query string.
query += (query === "" ? "?" : "&") + deviceParam;

window.location.search = query; // page should reload
CD Sanchez