javascript - 跨域脚本问题

标签 javascript jquery html css

我正在研究这个“随机报价机”元素。

$(document).ready(function() {

  getQuote();

  $("#new-quote").on("click", getQuote);

  function getQuote() {
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?", function(a) {
      var quote = "";
      var author = "";
      author = a[0].title;
      quote = a[0].content;
      $(".author").html(author);
      $("#quote").html(quote);
      $("#share-button").attr("href", 'https://twitter.com/intent/tweet?text=' + "\"" + $('#quote > p').html() + "\" - " + author);
    })
  };
});

问题: 我不知道跨域脚本问题。而我面临的问题是我无法获取 API 的数据。因此人们建议在 URL 中添加 "&_jsonp"。但现在即使添加它仅在我的浏览器发送 'http' 请求而不是 'https' 时才有效 当浏览器发送 https 请求时,这条消息会显示在我的 chrom 开发控制台中:

jquery-2.2.4.min.js:4 混合内容:位于“https://codepen.io/faisal1337/full/ZOvgNR/”的页面' 通过 HTTPS 加载,但请求了不安全的脚本 ' http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=jQuery22407926761305727481_1469082997979&_=1469082997982 '.此请求已被阻止;内容必须通过 HTTPS 提供。

所以“&_jsonp”会让恶意代码在我的网站上运行。我只想让页面正常运行,无论请求是'http' 还是'https'。有解决办法吗?

最佳答案

不要使用 http://x.comhttps://x.com 使用 //x.com .. .一个http页面将使用http,一个https页面将使用https

换句话说,该页面将使用与该页面加载的请求相同的协议(protocol)(http 与 https)

关于javascript - 跨域脚本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38496837/

相关文章:

javascript - 下拉菜单推送父菜单项

javascript - jQuery : Ajax is not been called first

javascript - 将更改应用于 angular.js 中由scope.$apply 获取的模型

javascript - 使用 (window).resize 实现响应式布局的多个脚本

仅当向上滚动时 Jquery 粘性导航

html - CSS如何使中间的元素在其兄弟向下跳之前收缩

javascript - 在 React 和 Vanilla Javascript 中输入数字 `e` 时不会调用 onChange

javascript - 默认情况下向对象添加属性

jquery - bootstrap下拉顶级导航制作可点击的链接

html - 如何使网站中的元素始终适合浏览器大小