我是可怕的,在Javascript中,提前让对不起什么,我要继续前进,并假设是一个令人惊讶的愚蠢的问题。
I'm horrible at Javascript, so sorry in advance for what I'm going to go ahead and assume is an amazingly stupid question.
我只是试图执行一个GET请求到GitHub的公开回购的API给定用户,并返回值作为JSON。
I'm simply trying to perform a GET request to GitHub's public repo API for a given user, and return the value as JSON.
下面的功能我想要使用:
Here's the function I'm trying to use:
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'json',
type: 'get',
success: function(data) {
alert('raw data: ' + data)
var json_response = $.parseJSON(data);
alert(json_response);
}
});
}
这是返回NULL数据。而在控制台中,我看到无法加载资源:取消
。我知道网址是正确的,因为如果我跑卷曲
的URL,它返回预期的数据。
This is returning Null for data. And in the console, I see Failed to load resource: cancelled
. I know the URL is correct, because if I run curl
on the url, it returns the expected data.
推荐答案
jQuery的AJAX功能支持JSONP,它允许跨域请求(你需要,因为你试图请求github.com数据从另一个域)。
jQuery's ajax function supports JSONP which allows cross-domain requests (which you need because you're trying to request data from github.com from another domain). Just change the dataType from 'json' to 'jsonp';
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'jsonp',
type: 'get',
success: function(data) {
var json_response = data;
alert(data);
}
});
}
更新:它的进口地注意到,端品脱(这种情况下github.com的API中)具有支持JSONP这个工作。它不会对任何跨域请求guarnateed解决方案在评论中指出的。
UPDATE: It's import to note that the end pint (in this case github.com's API) has to support JSONP for this to work. It's not a guarnateed solution for ANY cross-domain request as pointed out in the comments.
相关推荐
最新文章