How do I use the Deezer Api?

时光总嘲笑我的痴心妄想 提交于 2019-12-12 01:33:02

问题


I'm trying to use the deezer api to look up artists and display their name and image using Jquery. Here's my code:

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

but it just won't work. The code seems fine, but it keeps throwing up this error message, which I haven't a clue about or how to fix:

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.

How do I get it to work?


回答1:


The error is thrown because your browser is blocking the request. Because you execute this from javascript from your own site or maybe localhost, you do a cross-site request by calling a different url (the Deezer url). There are multiple ways to solve this problem.

  1. Try the following 'hack' with 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>");
    
             }
    });
    

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

Or 2. You route the request through your own server. With a server side language like php you do the request to the Deezer Api, and with jQuery you call that php page.



来源:https://stackoverflow.com/questions/23185964/how-do-i-use-the-deezer-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!