Twitter oEmbed跨源请求被阻止

时间:2015-03-11 16:36:11

标签: javascript ajax twitter oembed

我正在尝试使用Twitter oEmbed API发出嵌入式推文请求。代码现在非常简单:

xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}

xmlhttp.open("GET", "https://api.twitter.com/1/statuses/oembed.json?id=507185938620219395", true);
xmlhttp.send();

我在Firefox中收到了跨源请求阻止错误。我做错了什么?

2 个答案:

答案 0 :(得分:1)

答案是“使用jsonp”

$.ajax({
  type:     "GET",
  url:      "http://api.twitter.com/1/statuses/oembed.json?id=507185938620219395",
  dataType: "jsonp",
  success: function(data){
    console.log(data);
  }
});

答案 1 :(得分:0)

https://ctrlq.org/code/19933-embed-tweet-with-javascript

这是修复错误的解决方法

<!--
  Written by Amit Agarwal amit@labnol.org
  Paste this anywhere between the body tag
-->
 
<style>
 
  #tweet {
    width: 400px !important;
  }
 
  #tweet iframe {
    border: none !important;
    box-shadow: none !important;
  }
 
</style>
 
<div id="tweet" tweetID="515490786800963584"></div>
 
<script sync src="https://platform.twitter.com/widgets.js"></script>
 
<script>
 
  window.onload = (function(){
 
    var tweet = document.getElementById("tweet");
    var id = tweet.getAttribute("tweetID");
 
    twttr.widgets.createTweet(
      id, tweet, 
      {
        conversation : 'none',    // or all
        cards        : 'hidden',  // or visible 
        linkColor    : '#cc0000', // default is blue
        theme        : 'light'    // or dark
      })
    .then (function (el) {
      el.contentDocument.querySelector(".footer").style.display = "none";
    });
 
  });
 
</script>