-4

its my code for editing image src with output from json request everything works before return but when i'm write code to return output its getting error, dont changing image src.

$(function(){
$( ".plimg" ).attr(
"src",
function( index ){
track = '212';
artist = 'azealea banks';
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=track.search",
        {
          track: track,
          artist: artist,
          api_key: "ca86a16ce762065a423e20381ccfcdf0",
          format: "json",
          lang: "en",
            limit: 1        },
function(data) {
var output = data.results.trackmatches.track.image[0]["#text"]; 
});

    return output;  

}
);

});
4

2 回答 2

5

it is because $.getJSON is asynchronous, so the attr callback always return undefined as the attribute value.

The solution will to send the ajax request first and in its callback set the attribute value

$(function() {

    var track = '212';
    var artist = 'azealea banks';
    $.getJSON("http://ws.audioscrobbler.com/2.0/?method=track.search", {
        track : track,
        artist : artist,
        api_key : "ca86a16ce762065a423e20381ccfcdf0",
        format : "json",
        lang : "en",
        limit : 1
    }, function(data) {
        var output = data.results.trackmatches.track.image[0]["#text"];
        $(".plimg").attr("src", output);
    });
});
于 2013-08-26T07:23:17.450 回答
1

Another way to do it is by making the ajax call synchronous

$(function () {
    $(".plimg").attr("src",

    function (index) {
        track = '212';
        artist = 'azealea banks';

        var output;

        $.ajax({ //instead of getJSON as the function does not allow configurations.
            url: "http://ws.audioscrobbler.com/2.0/?method=track.search",
            data: {
                track: track,
                artist: artist,
                api_key: "ca86a16ce762065a423e20381ccfcdf0",
                format: "json",
                lang: "en",
                limit: 1
            },
            async: false, //making the call synchronous
            dataType: 'json', //specifying JSON type
            success: function (data) {
                output = data.results.trackmatches.track.image[0]["#text"];
            }

        });
        return output;
    });
});
于 2013-08-26T07:41:40.330 回答