2017-06-18 39 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