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

时间:2023-05-14
本文介绍了从 GitHub 读取代码作为网页中的文本(原始)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试从我的 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 with Content-Type: text/plain instead of Content-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 读取代码作为网页中的文本(原始)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何使用包含文件和发布数据的 JavaScript 创建 AJAX 请求 下一篇:如何在 firefox 插件中使用 Javascript 将图像上传到 ImgBB API

相关文章