使用jQuery.ajax()保存匿名github gist

for*_*sto 5 jquery gist github github-api

我在使用jQuery.ajax()Gistub发布要点时遇到了麻烦.创建了gist,响应是201 Created,但Firebug中的响应选项卡为空,并且命中了错误回调.

  var data = {
    "description": "posting gist test",
    "public": true,
    "files": {
      "test.txt": {
        "content": "hello gist!"
      }
    }
  }
  $.ajax({
    url: 'https://api.github.com/gists',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify(data)
  })
  .success( function(e) {
    console.log(e);
  })
  .error( function(e) {
    console.warn("gist save error", e);
  });
Run Code Online (Sandbox Code Playgroud)

令人沮丧的是,它在jsfiddle中运行良好:http://jsfiddle.net/vXpCV/


也许这就是问题所在.jsFiddle获得不同的响应头:

Access-Control-Allow-Cred...    true
Access-Control-Allow-Orig...    http://fiddle.jshell.net
Access-Control-Expose-Hea...    Link, X-RateLimit-Limit, X-RateLimit-Remaining, X-OAuth-Scopes, X-Accepted-OAuth-Scopes
Connection  keep-alive
Content-Length  1093
Content-Type    application/json; charset=utf-8
...
Run Code Online (Sandbox Code Playgroud)

And*_*aus 6

Forresto自己的答案是完全有效的:

将我的http://local.dev/添加到https://github.com/settings/applications似乎解决了这个问题.

...但只要这个答案出现在Gist + jQuery的谷歌搜索时,就应该对正在发生的事情进行解释.

浏览器存在称为同源策略的安全问题.它禁止网页与除加载页面之外的服务器进行通信,因此这基本上不起作用.有一种称为JSONP的解决方法技术,但它仅适用于GET请求,而此示例具有POST.

然后是这种称为跨源资源共享(CORS)的新技术.它允许在现代浏览器中打开的页面使用旧的AJAX与其他服务器通信.

GitHub API 仅接受来自GitHub上注册为OAuth应用程序的域的CORS请求.当jQuery发送POST请求时,它将OriginHTTP标头设置为等于从其启动的站点的域.

但我应该说,对我来说,即使有一个乱七八糟的Origin标题,剪辑也会解决.它工作,我不知道为什么.:)


for*_*sto 2

将我的添加http://local.dev/https://github.com/settings/applications似乎可以修复它。