javascript - 从 GitHub 读取代码作为网页中的文本(原始)

标签 javascript jquery github xmlhttprequest

我正在尝试从我的 GitHub 存储库中读取一些源代码(C 语言)以在我的网页中显示为文本。我可以通过 https://raw.github.com 以原始模式访问代码.

我正在使用 jQuery GET 函数读取数据,但它不起作用。问题与 XMLHttpRequest 和 Access-Control-Allow-Origin 有关,但尽管我在 stackoverflow ( XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin ) 上发现了一些相关问题,但它对我不起作用。我什么都试过了。

我的 jQuery 代码:

<script type="text/javascript">
  $(document).ready(function() {
    var url = 'https://raw.github.com/raysan5/raylib/master/examples/ex01_basic_window.c';

    $.get(url, function(data) { 
        $('#code').text(data);
      }, 'text');
    });
</script>

拜托,有人可以帮我解决这个问题吗?非常感谢!

最佳答案

您可以尝试删除 raw 和 github 之间的点:

https://rawgithub.com/raysan5/raylib/master/examples/ex01_basic_window.c

参见 rawgithub.com , 也在这个 blog post 中解释:

GitHub discourages this, since they want repo owners to use Github Pages to host specific versions of their files. They discourage it by serving files from the “raw” domain with Content-Type: text/plain instead of Content-type:application/javascript.

This wasn’t a problem until recently, when Google Chrome implemented a security fix that prevents JavaScript from being executed if it has an incorrect Content-type.
This makes sense when you’re viewing pages outside of your control. But when it’s you who’s deciding what scripts to include, it’s a hassle.

作为Rob W comments below :

It's worth mentioning that the only reason that this web service solves the OP's problem is that it includes the Access-Control-Allow-Origin: * response header.

关于javascript - 从 GitHub 读取代码作为网页中的文本(原始),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20161677/

相关文章:

git - 文件超出了 git 的大小,即使它已缩小到限制以下

git - 'git remote add' 是否只为同一个存储库创建别名?

eclipse - 使用 EGit 克隆存储库导入但不允许我导入项目

javascript - 标记更新位置

java - 在脚本 (javascript) 标签内使用 JSTL 是一种好习惯吗?

php - 刷新时输入值不会更改为其默认值

javascript - 使用 RequireJS knockout 自定义 Bootstrap 绑定(bind)错误

jquery - 重置表单输入的默认行为

javascript - THREE.js 通过对象克隆实现多个 Canvas 的多个 View 。陷阱?

javascript - 加载/重新加载页面时隐藏验证输出标记 (✘) 符号隐藏