Optimal jQuery and REST

91 views Asked by At

I am writing code using the Blizzard World of Warcraft Armory API. It's restful but I wanted to know if my code is optimal and what can I do to improve it? It works fine I just need to make sure I've made good use of data fetching or not.

Here is the basic HTML

<div id="title">Test</div>
<div id="chevoPoints">Test</div>
<div id="stat">Test</div>
<div id="realm">Test</div>
<div id="race">Test</div>
<div id="items">Test</div>
<img id="thumbnail" src="" />

Here is the java

$(document).ready(
        //Fetch RESTful data
        function getSite(){
            $.ajax({
                url: "http://eu.battle.net/api/wow/character/server/character?fields=titles,achievements,appearance,feed,stats,races,items&jsonp=GoGet",
                type: 'GET',
                dataType: 'jsonp'
                });
            }
        );  

        //Display the data
        function GoGet(data) {
            $("#title").html(data.name),
            $("#chevoPoints").html(data.achievementPoints),
            $("#stat").html(data.stats.armor),
            $("#realm").html(data.realm),
            $("#race").html(data.race),             
            $("#items").html("The back is called" + "&nbsp;" + data.items.back.name + "&nbsp;" + "and looks like" + "&nbsp;" + "<img src=http://media.blizzard.com/wow/icons/56/" + data.items.back.icon + ".jpg />"),
            $("#thumbnail").attr('src', "http://eu.battle.net/static-render/eu/" + data.thumbnail)
        ;}      
1

There are 1 answers

1
Jan_dh On

It look quiet ok, although I add at least couple of things:

 data: {format: 'json' },   //or any other format the data wil return
 error: { function(){alert('Something went wrong');}  //error-handling, what happens when no data was retrieved

Then depending on what you want to do you could also add some caching etc. to the request. A good read on all the optional parameters can be found here: http://www.sitepoint.com/use-jquerys-ajax-function/.

Edit: if your succes-response has multiple items you can loop through them like this:

 success: function (response) {
       //your list
       var t = $("<ul id='nameList'></ul>");
       //loop through the different items
       for (var i=0; i<response.d.length; i++) {
             //for each item you do stuff here, for example, wrap the name in a list-item
             i.name.appendTo(t).wrap("<li></li>")      
  });

You can also do this with $.each

 succes: $.each(response, function(index, data){
         //do stuff   
 });