views:

143

answers:

2

Hello all! I'm trying to take a URL's hash value, send it through a function, turn that value into an object, but ultimately send the value to JSON. I have the following setup:

function content(cur){
    var mycur = $H(cur);
    var pars = "p="+mycur.toJSON();
    new Ajax.Updater('my_box', 'test.php', {
      parameters: pars
    });
}   

function update(){
    if(window.location.hash.length > 0){
        content(window.location.hash.substr(1)); // Everything after the '#'
    }   
}

var curHashVal = window.location.hash;
window.onload = function(){
    setInterval(function(){
        if(curHashVal != window.location.hash){
            update();
            curHashVal = window.location.hash;
        }
        },1);
    }

But for some reason, I can't seem to get the right JSON output. It will either return as a very large object (1:"{",2:"k") or not return at all. I doubt that it is impossible to accomplish, but I've exhausted most of the ways I can think of.

Other ways I've tried were "{" + cur + "}" as well as cur.toObject(), however, none seemed to get the job done.

Thanks for the help!

EDIT: As an end result, I'd like the URL (say product:3,confirmed:1) to be returned as {"product":3,"confirmed":1}

+1  A: 

A typical implementation of toJSON() needs either an Array or an Object as the top-most element. Sonsomethig like this will probably work:

var pars = {p: myCur}; pars = pars.toJSON();

Mark Bessey
A: 

First of all native JSON support and the toJSONmethod is not available in all browsers. Older browsers like IE 6/7 or Firefox 2/3 do not support it. You should use a JSON library like json2 by Douglas Crockford. Second I would suggest to use the stringify method of the global JSON object instead of the toJSON function. In my tests

JSON.stringify("...")

works just fine.

Fabian Jakobs