我正在尝试从我的 GitHub 存储库中读取一些源代码(C 语言),以便在我的网页中显示为文本.我可以通过 https://raw.github.com 以原始模式访问代码.
I'm trying to read some source code (C language) from my GitHub repository to be shown as text in my webpage. I can access the code in raw mode through https://raw.github.com.
我正在使用 jQuery GET 函数来读取数据,但它不起作用.问题与 XMLHttpRequest 和 Access-Control-Allow-Origin 有关,但是尽管我在 stackoverflow 上发现了一些相关问题(XmlHttpRequest 错误:Access-Control-Allow-Origin 不允许使用 Origin null)它对我不起作用.我什么都试过了.
I'm using jQuery GET function to read the data but it doesn't work. Problem is related with XMLHttpRequest and Access-Control-Allow-Origin but, despite I found some related question on stackoverflow (XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin) it didn't work for me. I tried everything.
我的 jQuery 代码:
My jQuery code:
<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>
请问,有人可以帮我解决这个问题吗?非常感谢!
Please, could someone help me with this issue? Many thanks!
你可以尝试删除raw和github之间的点:
You could try and delete the dot between raw and github:
https://rawgithub.com/raysan5/raylib/master/examples/ex01_basic_window.c
参见 rawgithub.com,在这个 博文:
GitHub 不鼓励这样做,因为他们希望 repo 所有者使用 Github Pages 来托管其文件的特定版本.他们通过使用 Content-Type: text/plain
而不是 Content-type:application/javascript
提供来自raw
"域的文件来阻止它.
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
.
直到最近,当 Google Chrome 实施了一个安全修复程序,如果 JavaScript 的 Content-type
不正确,这将阻止 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 以下评论:
值得一提的是,此网络服务解决 OP 问题的唯一原因是它包含 Access-Control-Allow-Origin: *
响应标头.
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.
这篇关于从 GitHub 读取代码作为网页中的文本(原始)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!