从javascript使用github API的示例 [英] Example of using github API from javascript
问题描述
我已经在网上搜索了一段时间,但找不到如何使用 GitHub API 来自普通的客户端javascript(没有node-js,jquery等)。我想要一些像authenticate那样的东西,然后推送一个blob,尽可能简单地让我理解它。不应该太复杂,我打赌你可以用十几行代码做到这一点,但我不太了解ajax,json和jsonp。
I've been searching on the web for some time and couldn't find an example of how to use the GitHub API from 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.
Can你举个例子让我开始?
Can you provide an example to get me started?
谢谢!
编辑发现这个: http://blog.vjeux.com/category/javascript ,但我仍然对于什么感到困惑正是这个过程的步骤。
edit: found this: http://blog.vjeux.com/category/javascript, but I'm still confused as to what are exactly the steps of the process.
推荐答案
如果你想使用vanilla JavaScript(即没有框架),你需要使用 XMLHttpRequest
对象。 XMLHttpRequest
为AJAX实现提供了核心。
If you're looking to use with vanilla JavaScript (i.e. no framework), you need to play around with the XMLHttpRequest
object. The XMLHttpRequest
provides the core for AJAX implementations.
尽管 XMLHttp
前缀,您不仅限于XML或HTTP。您可以检索任何数据类型(例如JSON)并使用其他协议,例如FTP。
Despite the XMLHttp
prefix, you're not limited to XML or HTTP. You can retrieve any data type (such as JSON) and use other protocols such as FTP.
假设我们想要 GET
来自GitHub的用户信息。通过浏览器,我们可以通过访问 https://api.github.com/users/funchal 轻松提出请求。
使用JavaScript发送HTTP请求与 XMLHttpRequest
一样简单:
Say we'd like to GET
your 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
:
// 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()
如果你从JavaScript控制台开始,你可能会感到有点失望:什么都不会立即发生。您必须等待服务器响应您的请求。从您创建实例化请求对象到服务器响应之间,对象将经历一系列状态更改,由 readyState
属性的值表示:
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 readyState
property:
- 0
UNSENT
:open()
未命名 - 1
已打开
:send()
未被叫 - 2
HEADERS_RECIEVED
:标题和状态在send()
之后可用 - 3
LOADING
:responseText
仍在下载 - 4
DONE
:Wahoo!
- 0
UNSENT
:open()
uncalled - 1
OPENED
:send()
uncalled - 2
HEADERS_RECIEVED
: headers and status are available after asend()
- 3
LOADING
: theresponseText
is still downloading - 4
DONE
: Wahoo!
一旦完成,你可以检查数据的响应
属性:
Once all is finished, you can check the response
attribute for the data:
request.readyState // => 4 (We've waited enough)
request.response // => "{whatever}"
使用 XMLHttpRequest#open()
,您有几个选择可以考虑。这是方法签名:
When using XMLHttpRequest#open()
, you have a few options to consider. Here's the method signature:
void open(
DOMString method,
DOMString url,
optional boolean async,
optional DOMString user,
optional DOMString password
);
第三个参数,默认为true,指示响应是否应异步进行。如果将其设置为 false
,则必须等到 #send()
的响应完成后返回,你将付出阻止整个程序的代价。因此,我们以异步方式编码,以便我们的程序即使在我们等待时也能保持响应。这种异步性是通过使用和事件监听器(a.k.a.事件处理程序)和回调函数来实现的。
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 asynchronous fashion 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.
假设我们只想在响应到达时将响应转储到控制台。我们首先需要创建一个我们想要执行的回调函数 onload
:
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
:
function dumpResponse() {
// `this` will refer to the `XMLHTTPRequest` object that executes this function
console.log(this.responseText);
}
然后我们将此回调设置为<$ c $的监听器/处理程序c> onload 由 XMLHttpRequest
界面定义的事件:
Then we set this callback as the listener/handler for the onload
event defined by the XMLHttpRequest
interface:
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()
现在,因为你将以字符串形式接收数据,您需要使用 JSON.parse()
解析字符串以执行任何有意义的操作。假设我想调试您的公共存储库的数量以及您的名称。我可以使用此函数将字符串解析为JSON,然后我可以提取我想要的属性:
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:
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!
参见 W3C规范和 Mozilla开发者网络,了解有关 XMLHttpRequest
的更多信息。
See the W3C spec and the Mozilla Developer Network for more info on XMLHttpRequest
.
这篇关于从javascript使用github API的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!