my first jsonp

Just saying that jsonP is amazing. That P stands for padding, but I think of it as standing for procedure.

So I had my own server with a webpage that would show me music that I listend to. It did this with a server-side request to last.fm to get my listening history.

However, then I moved my site to github, and I couldn't run any server-side code. So now I need the client to make a request to last.fm to get my listening history. AJAX you say? But our betters have decided that making AJAX requests to other domains is bad, and last.fm is on another domain.

But, it's ok for the src attribute in a <script> tag to reference any domain. So you can dynamically add a <script> tag with a src attribute that effectively makes an API call to last.fm. The only issue now is, how do you see the results? If last.fm just fills the script with JSON, it will be parsed by the client, and promptly forgotten. So instead of getting a script like {"some" : "json"}, you instead want doSomethingWith({"some" : "json"}), where the doSomethingWith(...) is padding, or a procedure. Now if you implement doSomething, and then add the <script> tag, then doSomething will be called with the JSON data you want. Horray.

To see this in action, see: http://glittle.org/#music

No comments:

Post a Comment