我的代码用于编辑图像src与json请求的输出在返回之前一切正常但是当我编写代码以返回输出时获取错误,不要更改图像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;
}
);
});
答案 0 :(得分:5)
因为$.getJSON
是异步的,所以attr
回调总是返回undefined作为属性值。
解决方案将首先发送ajax请求并在其回调集中发送属性值
$(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);
});
});
答案 1 :(得分:1)
另一种方法是通过使ajax调用同步
$(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;
});
});