2017-06-18 70 views
0

我很亲密!并有点困惑......所以告诉我,如果我是过分复杂的事情。Giphy API:使用jQuery为随机GIF设置新的源属性

我正在使用公众Giphy API拉起一个随机gif(标签=狗在下面的例子中),并希望每次点击一个按钮时遍历新的gif。

在下面的例子中,我得到控制台记录“成功”,我只是不能完全弄清楚如何设置新的随机URL作为源。

任何帮助表示赞赏,在此先感谢!

HTML:

<div class="iframe"> 
    <iframe src="https://giphy.com/embed/26FmRLBRZfpMNwWdy" id="giphy-embed"> 
    </iframe> 
</div> 

<button type='button' class="btn btn-default" id="new"> New GIF 
</button> 

JS/jQuery的:

$("#new").click(function() { 
    var gif = $('#giphy-embed').attr('src', function(newGIF){ //This is where it will go! 
    $.ajax ({ 
    url: "//api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=dog", 
    type: "GET", 
    success: function(response) { 

     console.log("success"); //This is what I get, just need to set the new URL as the src 
    }, 
    error: function(e) { 
     console.log("uh oh"); 
     } 
    }); 
    }); 

}); 

回答

0

尝试更新的iframe src作为成功的部分功能来代替。

$("#new").click(function() { 
//This is where it will go! 
    var imgSrc; 
    $.ajax ({ 
    url: "//api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=dog", 
    type: "GET", 
    success: function(response) { 
     // console.log(response); 
     imgSrc = response.data.image_url; 
     $("#giphy-embed").attr("src", imgSrc); 
     return false; 
    }, 
    error: function(e) { 
     console.log("uh oh"); 
     } 
    }); 
}); 
+0

我看到你从哪里来,我喜欢它! 它只是不太工作。控制台提出了整个Ajax响应和所有。 这是CodePen的链接 https://codepen.io/benthom21/pen/qjRzJV?editors=1011 –

+0

它工作正常 - 在您的本地主机或服务器上试用它。 codepen上存在混合内容错误,因为它通过https加载,并且giphy是http。 – partypete25

+0

我的意思是response.data.image_url是http。我做了一个调整,以更新图像的src ID。这将工作。 imgSrc = response.data.id; $(“#giphy-embed”)。attr(“src”,“https://giphy.com/embed/"+imgSrc); – partypete25