从GitHub读取网页中的文本(原始)代码 [英] Reading code from GitHub as text (raw) in a web page
问题描述
我正在尝试从我的GitHub存储库中读取一些源代码(C语言),以便在我的网页中显示为文本。我可以通过 https://raw.github.com 访问原始模式下的代码。
我使用jQuery GET函数来读取数据,但它不起作用。问题与XMLHttpRequest和Access-Control-Allow-Origin有关,但是,尽管我在stackoverflow上发现了一些相关问题( XmlHttpRequest错误:原始null不被访问控制允许来源)它不适合我。我尝试了一切。
我的jQuery代码:
<脚本类型= 文本/ 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 ,同时在博客文章:
GitHub不鼓励这样做,因为他们希望repo所有者使用Github Pages托管他们文件的特定版本。他们通过使用
Content-Type:text / plain
来代替raw
域中的文件来阻止它c $ c> Content-type:application / javascript 。
直到最近Google Chrome实施安全修复如果它有一个不正确的
com / users / 938089 / rob-w> Rob W 评论下面:Content-type
,则阻止JavaScript被执行。
当您在控件之外查看页面时,这是有意义的。但是,当你决定要包含什么脚本时,这是一件麻烦事。
值得一提的是唯一的原因这个Web服务解决OP的问题是它包含了
Access-Control-Allow-Origin:*
响应头。
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.
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.
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!
解决方案You could try and delete the dot between raw and github:
https://rawgithub.com/raysan5/raylib/master/examples/ex01_basic_window.c
See rawgithub.com, also explained in this 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.As 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.
这篇关于从GitHub读取网页中的文本(原始)代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!