tags:

views:

20

answers:

1

I have a simple jquery script as follows:

$('a').click(function() 
    {
        //get the id of the song we want to play
        var song_id = $(this).attr("id");

        //do a get request to get the information about the song
        $.get("http://www.site.com/v4/ajax/get_song_info.php", { id: song_id, }, function(data)
        {
            alert("Data Loaded: " + data);
        });
        //alert( song_id );
    });

I have gotten it to work and it returns several bits of data 'artist' 'title' 'song duration' and so on.

How do I process my 'data' so I can then update my page with each bit. In this case I want to set a series of '' to hold each of the values returned.

Thanks.

A: 

Best practice would be to use a JSON encoding.

Whatever server-language you are using, encode your data as JSON object and send it with the mime-type application/json.

Javascript/jQuery side make a call to .getJSON() which is aquivalent to

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

However, if you are using jQuery 1.4.x, you now have a JSON object in your data variable. In a previous version you need to explicitly parse the incoming data into a JSON object. For instance

if(window.JSON) data = window.JSON.parse(data);

This will create a valid Javascript Object which you can treat and access like

data.artist

(Of course you need to create such an object structure serverside before sending)

jAndy
I am using PHP so instead of echo 'whatever' i need to do whatever it is that PHP does to output a JSON object?
ian
If you’re on PHP5, try `echo json_encode(aPHPObject)`.
Evadne Wu