2014-01-20 73 views
0

我真的不知道我在做什么错在这里。我无法重新分配变量poster_path与在JSON调用中获取的海报路径。现在我惊讶的是,我试过async to false。它不起作用。async false with JSON-call not working(javascript)

我已经通过多个现有的答案,如这一个(How do I return the response from an asynchronous call?)搜索,但还没有找到任何解决方案。

function getPoster(id) { 
var poster_path = null; 

$.getJSON("https://api.moviedb.org"+id+"?", {async: false}, function(data) { 
     poster_path = data.poster_path; 
    } 
} 

PS:此示例中API调用已被有意缩短。我知道它是有效的,它会返回正确的数据。

+0

这可能是有帮助的希望这样的:https://stackoverflow.com/questions/14152276/themoviedb -json-api-with-jquery – Andy

+1

第二个参数是数据,而不是选项,请参阅这里的文档http://api.jquery.com/jquery.getjson/。改为使用$ .ajax。 – Andrew

回答

1

$.getJSON功能是$.ajax方法的简写版本。因为它是简写版本,所以它会做出一些假设,其中一个是呼叫将是异步

如果由同步呼叫不推荐那么你要像

$.ajax({ 
    'async'   : true, 
    'dataType'  : 'json', 
    'contentType'  : 'application/json', 
    'url'    : 'https://api.moviedb.org'+id+'?', 
    'success'   : function (data){ 
         poster_path = data.poster_path; 
         } 
}); 
相关问题