Reading code from GitHub as text (raw) in a web page

北战南征 提交于 2020-01-01 19:14:32

问题


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!


回答1:


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 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.

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.



来源:https://stackoverflow.com/questions/20161677/reading-code-from-github-as-text-raw-in-a-web-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!