我正在尝试从我的 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 withContent-Type: text/plain
instead ofContent-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/