views:

286

answers:

2

I have the following code to display JSON results from an AJAX request as an unordered list. It works well enough in Safari but on Mobile Safari on the iPhone the raw data displays but the UL does not. In fact the for loop isn't triggered.

$("#results").append(data);

var songdata = JSON.parse(data);

var i = 0;

for (i=0;i<=songdata.total;i++)
{
    alert(i);
    var songhtml = "<ul><li><img src=\"" + songdata.data[i].artwork + "\" /></li><li>" + songdata.data[i].title + "</li><li>" + songdata.data[i].artist + "</li><li>" + songdata.data[i].length + "</li><li>" + songdata.data[i].listen + "</li></ul>";
    $("#results").append(songhtml);

}

I expect it's to do with an error of mine, thank you in advance...

Ben

+1  A: 

I have run into a similar problem when trying to use a variable set with JSON.parse() and viewing the results via the mobile safari browser on an itouch: mobile safari debugger reveals that it,

can't find the variable JSON

.

After doing some googling on the error msg there is chatter that mobile safari does not currently have JSON.parse support. Which would explain why your for-loop never triggers because your var songdata never gets set. If you find a workaround please post!

SuZi
Wow thanks for coming back to this.
Ben
A: 

I also found this to be the case on my 3g running 3.1.2, but worked on my iPhone 4. Anyway, to avoid this error I am now including Douglas Crockford's json2.js file, which detects whether or not the browser has support for JSON and if it doesn't implements its own. I (and I believe even Resig) recommend this over jQuery's parse functionality as it has support for stringify and also does not use eval at all. (jQuery does, or at least used, fall back to eval on older browsers). Here is the file you can download and host:

http://www.json.org/json2.js

Jesse Streb