2014-11-20 21 views
0

我正在使用暴雪魔獸世界Armory API編寫代碼。它很安靜,但我想知道我的代碼是否是最佳的,我可以做些什麼來改進它?它工作正常,我只需要確保我已經很好地使用了數據獲取或不。最佳jQuery和REST

這是基本的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="" /> 

這裏是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) 
     ;}  

回答

2

它看起來安靜好了,雖然我添加至少兩件事情:

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 

然後根據在你想要做的事情上,你也可以添加一些緩存等。有關所有可選參數的詳細信息,請參閱:http://www.sitepoint.com/use-jquerys-ajax-function/

編輯:如果您的更迭反應有這樣的多個項目可以遍歷他們:

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>")  
    }); 

您也可以用$。每個

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

感謝這個,一個問題做到這一點我有一些這樣的電話有多個結果,無論如何,我可以將它們顯示爲一個列表? – Yanayaya 2014-11-21 10:36:13

+0

當然,我會編輯我原來的回覆,秒。 – 2014-11-21 16:20:18