2014-04-20 64 views
0

我試圖用deezer api來查找藝術家,並使用Jquery顯示他們的名字和圖像。這是我的代碼:如何使用Deezer Api?

$.getJSON('http://api.deezer.com/search/artists?q='+q+'', 
    function(data) { 
     $("#artists").empty(); 
     $.each(data, function(i,item){ 

var y=item.picture; 

var z=x+y; 

     $("#artists").append("<div id='card_artist'><div id='cardimg' style='background-image: url("+ z +");'></div><div id='artistname' class='jtextfill'><span>" + item.name + "<span></div></div>"); 
    }); 
}); 

但它只是不會工作。代碼看起來很好,但它一直扔了此錯誤消息,我卻沒有一個關於線索或如何解決:

XMLHttpRequest cannot load http://api.deezer.com/search/artists?q=whatever. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我如何得到它的工作?

回答

0

由於您的瀏覽器阻止了請求,因此引發錯誤。因爲您可以從您自己的網站或本地主機的JavaScript執行此操作,因此您可以通過調用其他網址(Deezer網址)來執行跨網站請求。有多種方法可以解決這個問題。

  1. 試試下面的 '技巧' 與JSONP:

    // Using YQL and JSONP 
    $.ajax({ 
        url: "http://api.deezer.com/search/artists?q="+q, 
    
        // the name of the callback parameter, as specified by the YQL service 
        jsonp: "callback", 
    
        // tell jQuery we're expecting JSONP 
        dataType: "jsonp", 
    
        // tell YQL what we want and that we want JSON 
        data: { 
         format: "json" 
        }, 
    
        // work with the response 
        success: function(response) { 
         $("#artists").empty(); 
         $.each(data, function(i,item){ 
    
          var y=item.picture; 
    
          var z=x+y; 
    
          $("#artists").append("<div id='card_artist'><div id='cardimg' style='background-image: url("+ z +");'></div><div id='artistname' class='jtextfill'><span>" + item.name + "<span></div></div>"); 
    
         } 
    }); 
    

    來源:https://learn.jquery.com/ajax/working-with-jsonp/

或者2.你的路線,通過自己的服務器的請求。 使用像php這樣的服務器端語言,您可以向Deezer Api請求,並使用jQuery調用該PHP頁面。

+0

啊!!! * facepalm *我以錯誤的方式去討論它......我完全忘記了JSONP,感謝你清除它! – looserlf