How to embed twitter from URL using jQuery / JSON / oembed

It is very difficult for me to find a way to dynamically embed tweets in a web page. Ideally, I would like the user to enter the Twitter status URL (for example, https://twitter.com/robdelaney/status/329651129988288514 ), click the button, and you have the tweet inserted into the div.

Here is what I have so far:

$(document).ready(function(){ $("#resolve").click(function(){ var url = $("#retweet_form_url").val(); if (url==""){ $(".controls").addClass("error"); } else { $("#tweet_div").show(); $.ajax({ url: "https://api.twitter.com/1/statuses/oembed.json?url="+url, dataType: "jsonp", success: function(data){ // Derp! What do I do here? } }); } }) }) 

When I test this using the URL, I get the JSON response from Twitter, and not all the HTML code needed to embed the tweet, but when I try to parse it, I cannot get anything to appear in my div. Can someone point me in the right direction?

+6
source share
1 answer

data is an object containing the details of the tweet, including the html element containing the actual insert code. So:

 // ... success: function(data){ $("#tweet_div").html(data.html); } // ... 

 $(document).ready(function() { $("#resolve").click(function() { var url = $("#retweet_form_url").val(); if (url == "") { $(".controls").addClass("error"); } else { $("#tweet_div").show(); $.ajax({ url: "https://api.twitter.com/1/statuses/oembed.json?url=" + url, dataType: "jsonp", success: function(data) { $('#tweet_details').html(data.html); } }); } }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id=retweet_form_url value="https://twitter.com/robdelaney/status/329651129988288514" /> <button id=resolve>resolve</button> <div id=tweet_details></div> 
+7
source

Source: https://habr.com/ru/post/944079/


All Articles