views:

590

answers:

2

Hey,

I am using the following line of JQuery code:

$.get('/ajax/buy', {'categoryname':chosenSelected}, function(data) {
   data = JSON.parse(data);
...

However, when running it on IE7 I get error msg "JSON undefined:".

How can I use the parser with compatibility to IE7 (and all major browsers)?

Thanks in advance, Joel

+4  A: 

You don't need to parse JSON manually. You could use the getJSON function:

$.getJSON('/ajax/buy', { 'categoryname' : chosenSelected }, function(data) {

    // data will be already a parsed JSON object
});

The parse method you are trying to call is available in the json2 library.

Darin Dimitrov
Thanks!I can't find a similar $.postJSON function.Any special reason for that?
Joel
And if there really isnt any function like, it seems like Luc'as idea will be good:$.post('/ajax/buy', { 'categoryname' : chosenSelected }, function(data) {data = jQuery.parseJSON(data);
Joel
No, please nothing on earth will convince me that it's better to parse the JSON manually rather than using the built-in functionality in jQuery, I mean this makes you write more code and the more code you have to achieve the same thing the more chance you have to get it wrong.
Darin Dimitrov
If you want to use `post` then why not: `$.post('/ajax/buy', { 'categoryname' : chosenSelected }, function(data) { // data will already be parsed here });`
Darin Dimitrov
Why will the data be parsed already?"data" is a JSON created by "/ajax/buy"..I need to parse it somehow.
Joel
Because when jQuery performs an AJAX call and the server sends the correct `Content-Type` header it will automatically parse the data.
Darin Dimitrov
In that case, then why should get be different than post? Why is there a special getJSON function?
Joel
In this case it is not different. `$.get` will also automatically parse. The reason to have `getJSON` is to explicitly specify that this server method will only return JSON and never XML or HTML for example, while `$.get` can handle all cases.
Darin Dimitrov
A: 

You can use parseJSON available in jQuery.

Luca Matteis