Ajax调用到外部URL [英] Ajax call to external URL
问题描述
我正在尝试从我的个人Duolingo帐户访问一个或两个数据属性.当输入以下URL时,将返回一个JSON对象: http://www.duolingo.com/users/username (我已替换了我的ID网址中带有用户名").
I am trying to access on or two data attributes from my personal Duolingo account. When punching in the following URL a JSON object is returned: http://www.duolingo.com/users/username (I've replaced my id with "username" in the url).
var getDuolingoData = function() {
return $.ajax({
type: "get",
url: "http://www.duolingo.com/users/daniel692007&callback=?",
dataType: "json"
});
}
getDuolingoData().then(function(json) {
console.log(json.site_streak); // this log is causing the error
});
但是,当我尝试从返回的对象中记录密钥时,将以下错误记录到控制台:
When I try and log a key from the returned object, however, the following error is logged to the console:
未捕获到的SyntaxError:意外令牌<
Uncaught SyntaxError: Unexpected token <
Ajax对我来说还很陌生,Duolingo没有我所知道的API,并且由于这是一个外部URL,我相信由于CORS,dataType
必须设置为jsonp
.
Ajax is fairly new to me, Duolingo don't have an API that I know of and as this is an external URL I believe the dataType
must be set to jsonp
due to CORS.
是否有明显的原因导致我无法访问访问指定URL时可以看到的JSON对象?
Is there an obvious reason that I am not able to access the JSON object I can see when visiting the specified URL?
TY
推荐答案
我遇到了同样的问题.我无法使用jsonp解决它.我最终要做的是在控制器中进行操作,该控制器从外部URL接收json并将其发送到ajax调用.
The same issue happened to me. I was unable to solve it using jsonp. What i ended up doing was to make an action in the controller that recieved the json from external url and send it to the ajax call.
例如
return $.ajax({
type: "post",
url: "/ActionInProject/ProjectController",
});
然后,在Controller中,无论使用哪种服务器端语言,它都将有所不同.对我来说是C#,所以我做了
then in the Controller it will be different for whichever server side language is being used. For me it was C# so i did something like
[HttpPost]
public JsonResult ActionInProject()
{
using(HttpClient client = new HttpClient())
{
var response = client.GetAsync("someothersite.com/api/link");
return Json(client.GetAsync());
}
}
这篇关于Ajax调用到外部URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!