سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top