问题
I've been looking around for an answer to this question and have found mixed results...
My question is simple: How can I simply fetch a JSON file from a Github repository using either JQuery, JavaScript, or some sort of scripting? I've heard of a Github API and I've also heard about Github "raw" urls, but I want to know which would be the most efficient and standard method of doing something like this. Perhaps it would require PHP and make the server pull the repository off of the server?
If any are curious, I'm doing this to provide a simple localization layer. I have a JSON database of content-metadata that is in English and want to provide a means of letting users switch to different languages, add additional language support, and increase accessibility. Version control and maintaining the database is important to me, so GitHub felt like an obvious solution.
It would be a pain to manually pull content and synchronize the website myself. I would like to address it much like I address parsing my other JSON files, which is as follows:
$.getJSON("contentmetadata.json", function(data){
$.each(data.content, function(i, field){
<!-- data here -->
});
});
but instead of local data, I would like to fetch it from the Github servers. If I could do it with JQuery or JavaScript, that would be great, but I could also try to implement PHP or server-side functionality if that is the only reasonable option.
回答1:
just use the raw url of the json file. Bare in mind the cross domain policy.
回答2:
I would agree to use a raw data on fetching JSON file from GitHub repo
. It safe on most cases.
Use $.getJSON in jQuery is sufficient enough. The code below is just for an example.
var rawbase = 'https://raw.githubusercontent.com/';
var jsonloc = 'octocat/octocat.github.io/master/params.json';
$.getJSON(rawbase + jsonloc, function( data ) {
console.log(data);
//do what you want with data
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
来源:https://stackoverflow.com/questions/22403218/html-automatically-fetching-json-file-from-github-repo