javascript - Ajax 调用外部 URL

标签 javascript jquery json ajax

我正在尝试从我的个人 Duolingo 帐户访问一个或两个数据属性。当输入以下 URL 时,会返回一个 JSON 对象: http://www.duolingo.com/users/username (我已将网址中的 id 替换为“用户名”)。

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

});

但是,当我尝试记录返回对象中的 key 时,控制台会记录以下错误:

Uncaught SyntaxError: Unexpected token <

Ajax 对我来说相当新,Duolingo 没有我所知道的 API,并且由于这是一个外部 URL,我相信 dataType 必须设置为 jsonp 由于 CORS。

是否有明显的原因导致我无法访问访问指定 URL 时可以看到的 JSON 对象?

TY

最佳答案

同样的问题也发生在我身上。我无法使用 jsonp 解决它。我最终做的是在 Controller 中执行一个操作,从外部 url 接收 json 并将其发送到 ajax 调用。

例如

return $.ajax({
        type: "post",
        url: "/ActionInProject/ProjectController",
    });

然后在 Controller 中,无论使用哪种服务器端语言,它都会有所不同。对我来说,它是 C#,所以我做了类似的事情

[HttpPost]
public JsonResult ActionInProject()
{
   using(HttpClient client = new HttpClient())
   {
      var response = client.GetAsync("someothersite.com/api/link");
      return Json(client.GetAsync());
   }
}

关于javascript - Ajax 调用外部 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48903298/

相关文章:

javascript - jqGrid : open a customised form on click of 'Edit' button and after edit refresh that row

javascript - 在表单的隐藏字段中提交的 JSON 编码的 PHP 数组 - 在提交表单的页面中打印时给出奇怪的输出

javascript - 我无法使用 JS 访问元素的可视位置

javascript - 仅仅为了代码整洁而编写 jQuery 插件是个好主意吗?

jquery - 一起使用 load() 和 after()

asp.net-mvc - 如何从 ASP.NET MVC Web API 帖子中获取原始 JSON 字典?

json - 如何对流程图中的 y 轴字符串值进行排序

javascript - 为什么 Angularjs 调用 Controller 两次?

javascript - 使用 javascript(无 jQuery)将第一个元素之后的所有元素添加到 div

javascript - 嵌入的 js 文件不适用于 jQuery .load() 内容