从 javascript 使用 github API 的示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10341135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:32:52  来源:igfitidea点击:

Example of using github API from javascript

javascriptgithub-api

提问by Giovanni Funchal

I've been searching on the web for some time and couldn't find an example of how to use the GitHub APIfrom plain client-side javascript (no node-js, jquery etc). I wanted something like authenticate then push a blob, put as simply as possible so I can understand it. Shouldn't be too complicated, I bet you can do that in a dozen lines of code but I don't know a lot about ajax, json and jsonp.

我已经在网上搜索了一段时间,但找不到如何从普通客户端 javascript(没有 node-js、jquery 等)使用GitHub API的示例。我想要像验证这样的东西,然后推送一个 blob,尽可能简单,这样我就能理解它。应该不会太复杂,我打赌你可以用十几行代码做到这一点,但我对ajax、json和jsonp了解不多。

Can you provide an example to get me started?

你能提供一个例子让我开始吗?

Thanks!

谢谢!

edit:found this: http://blog.vjeux.com/category/javascript, but I'm still confused as to what are exactly the steps of the process.

编辑:发现这个:http: //blog.vjeux.com/category/javascript,但我仍然对这个过程的具体步骤感到困惑。

回答by fny

If you're looking to use with vanilla JavaScript (i.e. no framework), you need to play around with the XMLHttpRequestobject. The XMLHttpRequestprovides the core for AJAX implementations.

如果您希望使用 vanilla JavaScript(即没有框架),则需要使用该XMLHttpRequest对象。该XMLHttpRequest规定AJAX实现的核心。

Despite the XMLHttpprefix, you're not limited to XML or HTTP. You can retrieve any data type (such as JSON) and use other protocols such as FTP.

尽管有XMLHttp前缀,但您并不限于 XML 或 HTTP。您可以检索任何数据类型(例如 JSON)并使用其他协议(例如 FTP)。

Say we'd like to GETyour user information from GitHub. From a browser, we can easily make the request by visiting https://api.github.com/users/funchal. Sending an HTTP request in JavaScript is just as simple with XMLHttpRequest:

假设我们想GET从 GitHub 获取您的用户信息。在浏览器中,我们可以通过访问https://api.github.com/users/funchal轻松发出请求。在 JavaScript 中发送 HTTP 请求同样简单XMLHttpRequest

// Create a new request object
var request = new XMLHttpRequest();

// Initialize a request
request.open('get', 'https://api.github.com/users/funchal')
// Send it
request.send()

If you give this a go from a JavaScript console, you might feel a bit disappointed: nothing will happen immediately. You'll have to wait for the server to respond to your request. From the time you create the instantiate the request object till when the server responds, the object will undergo a series of state changes denoted by the value of the readyStateproperty:

如果您从 JavaScript 控制台试一试,您可能会感到有点失望:不会立即发生任何事情。您必须等待服务器响应您的请求。从您创建实例化请求对象到服务器响应时,该对象将经历一系列由readyState属性值表示的状态更改:

  • 0 UNSENT: open()uncalled
  • 1 OPENED: send()uncalled
  • 2 HEADERS_RECIEVED: headers and status are available after a send()
  • 3 LOADING: the responseTextis still downloading
  • 4 DONE: Wahoo!
  • 0 UNSENT:open()未调用
  • 1 OPENED:send()未调用
  • 2 HEADERS_RECIEVED: headers 和 status 在 a 之后可用send()
  • 3 LOADINGresponseText仍在下载
  • 4 DONE:哇!

Once all is finished, you can check the responseattribute for the data:

全部完成后,您可以检查response数据的属性:

request.readyState // => 4 (We've waited enough)
request.response // => "{whatever}"

When using XMLHttpRequest#open(), you have a few options to consider. Here's the method signature:

使用 时XMLHttpRequest#open(),您有几个选项需要考虑。这是方法签名:

void open(
   DOMString method,
   DOMString url,
   optional boolean async,
   optional DOMString user,
   optional DOMString password
);

The third parameter, which defaults to true, dictates whether the response should be made asynchronously. If you set this to false, you'll have to wait until the response is complete for #send()to return, and you'll pay the price of blocking your whole program. As such, we code in an asynchronousfashion so that our program remains responsive even while we wait. This asynchronicity is achieved by using and event listeners (a.k.a. event handlers) and callback functions.

第三个参数默认为 true,指示是否应异步进行响应。如果将此设置为false,则必须等到响应完成#send()才能返回,并且您将付出阻塞整个程序的代价。因此,我们以异步方式编码,以便我们的程序即使在等待时也能保持响应。这种异步性是通过使用 和 事件侦听器(又名事件处理程序)和回调函数来实现的。

Say we want to simply dump the response to the console once it arrives. We first need to create a callback function that we'd like to execute onload:

假设我们想在响应到达后简单地将响应转储到控制台。我们首先需要创建一个我们想要执行的回调函数onload

function dumpResponse() {
  // `this` will refer to the `XMLHTTPRequest` object that executes this function
  console.log(this.responseText);
}

Then we set this callback as the listener/handler for the onloadevent defined by the XMLHttpRequestinterface:

然后我们将此回调设置为接口onload定义的事件的侦听器/处理程序XMLHttpRequest

var request = new XMLHttpRequest();
// Set the event handler
request.onload = dumpResponse;
// Initialize the request
request.open('get', 'https://api.github.com/users/funchal', true)
// Fire away!
request.send()

Now since you'll be receiving the data as a string, you'll need to parse the string with JSON.parse()to do anything meaningful. Say I want to debug the number of public repositories you have along with your name. I can use this function to parse the string into JSON, and then I can pull the attributes I want:

现在,由于您将以字符串的形式接收数据,因此您需要解析字符串JSON.parse()以执行任何有意义的操作。假设我想调试您拥有的公共存储库数量以及您的姓名。我可以使用这个函数将字符串解析成JSON,然后我就可以拉取我想要的属性:

function printRepoCount() {
  var responseObj = JSON.parse(this.responseText);
  console.log(responseObj.name + " has " + responseObj.public_repos + " public repositories!");
}
var request = new XMLHttpRequest();
request.onload = printRepoCount;
request.open('get', 'https://api.github.com/users/funchal', true)
request.send()
// => Giovanni Funchal has 8 public repositories!

See the W3C specand the Mozilla Developer Networkfor more info on XMLHttpRequest.

W3C规范Mozilla开发者网络上的详细信息XMLHttpRequest