简体   繁体   English

Ajax调用到外部URL

[英]Ajax call to external URL

I am trying to access on or two data attributes from my personal Duolingo account. 我正在尝试从我的个人Duolingo帐户访问一个或两个数据属性。 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). 当在以下URL中打孔时,将返回JSON对象: http : //www.duolingo.com/users/username (我已将URL中的ID替换为“ username”)。

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: 但是,当我尝试从返回的对象记录密钥时,将以下错误记录到控制台:

Uncaught SyntaxError: Unexpected token < 未捕获到的SyntaxError:意外令牌<

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. Ajax对我来说还很陌生,Duolingo没有我所知道的API,并且由于这是一个外部URL,我相信由于CORS,必须将dataType设置为jsonp

Is there an obvious reason that I am not able to access the JSON object I can see when visiting the specified URL? 有明显的原因导致我无法访问访问指定URL时可以看到的JSON对象吗?

TY TY

The same issue happened to me. 我也遇到了同样的问题。 I was unable to solve it using jsonp. 我无法使用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. 我最终要做的是在控制器中进行操作,该控制器从外部URL接收json并将其发送到ajax调用。

For exmaple 例如

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

then in the Controller it will be different for whichever server side language is being used. 然后在Controller中,无论使用哪种服务器端语言,它都会有所不同。 For me it was C# so i did something like 对我来说是C#,所以我做了类似的事情

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

I tried your request with Postman and I found it not valid json in the respone you can find below what is returned of the server 我用Postman尝试了您的请求,但在服务器返回的内容下面可以找到响应中的无效json,

<!DOCTYPE html><html dir="ltr"><head><title>Duolingo</title><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"><meta name="robots" content="NOODP"><noscript><meta http-equiv="refresh" content="0; url=/nojs/splash"></noscript><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><meta name="apple-mobile-web-app-title" content="Duolingo"><meta name="google" content="notranslate"><meta name="mobile-web-app-capable" content="yes"><meta name="apple-itunes-app" content="app-id=570060128"><meta name="google-site-verification" content="nWyTCDRw4VJS_b6YSRZiFmmj56EawZpZMhHtKXt7lkU"><link rel="chrome-webstore-item" href="https://chrome.google.com/webstore/detail/aiahmijlpehemcpleichkcokhegllfjl"><link rel="apple-touch-icon" href="//d35aaqx5ub95lt.cloudfront.net/images/duolingo-touch-icon.png"><link rel="shortcut icon" type="image/x-icon" href="//d35aaqx5ub95lt.cloudfront.net/favicon.ico"><link href="//d35aaqx5ub95lt.cloudfront.net/css/ltr-9f45956e.css" rel="stylesheet"> <link rel="manifest" href="/gcm/manifest.json"></head><body><div id="root"></div><script>window.duo={"detUiLanguages":["en","es","pt","it","fr","de","ja","zs","zt","ko","ru","hi","hu","tr"],"troubleshootingForumId":647,"uiLanguage":"en","unsupportedDirections":[],"oldWebUrlWhitelist":["^/activity_stream$","^/admin_tools$","^/c/$","^/certification/","^/comment/","^/course/","^/course_announcement/","^/courses$","^/courses/","^/debug/","^/dictionary/","^/discussion$","^/event/","^/forgot_password$","^/guidelines$","^/help$","^/j$","^/mobile$","^/p/$","^/pm/","^/power_practice/","^/preview/.+/","^/quit_classroom_session","^/redirect/","^/referred","^/register_user$","^/reset_password","^/settings/reset_lang","^/skill_practice/","^/team/","^/teams$","^/topic/","^/translation/","^/translations$","^/translations/","^/troubleshooting$","^/ui_strings/","^/upload$","^/vocab","^/welcome$","^/welcome/","^/word","^/words$"]}</script><script>window.duo.version="c89bfb9"</script><script>!function(r){function n(t){if(e[t])return e[t].exports;var s=e[t]={i:t,l:!1,exports:{}};return r[t].call(s.exports,s,s.exports,n),s.l=!0,s.exports}var t=window.webpackJsonp;window.webpackJsonp=function(e,i,o){for(var c,a,f,d=0,u=[];d<e.length;d++)a=e[d],s[a]&&u.push(s[a][0]),s[a]=0;for(c in i)Object.prototype.hasOwnProperty.call(i,c)&&(r[c]=i[c]);for(t&&t(e,i,o);u.length;)u.shift()();if(o)for(d=0;d<o.length;d++)f=n(n.s=o[d]);return f};var e={},s={31:0};n.e=function(r){function t(){c.onerror=c.onload=null,clearTimeout(a);var n=s[r];0!==n&&(n&&n[1](new Error("Loading chunk "+r+" failed.")),s[r]=void 0)}var e=s[r];if(0===e)return new Promise(function(r){r()});if(e)return e[2];var i=new Promise(function(n,t){e=s[r]=[n,t]});e[2]=i;var o=document.getElementsByTagName("head")[0],c=document.createElement("script");c.type="text/javascript",c.charset="utf-8",c.async=!0,c.timeout=12e4,n.nc&&c.setAttribute("nonce",n.nc),c.src=n.p+""+({0:"js/vendor",1:"js/app",2:"strings/zh-TW",3:"strings/zh-CN",4:"strings/vi",5:"strings/uk",6:"strings/tr",7:"strings/tl",8:"strings/th",9:"strings/te",10:"strings/ta",11:"strings/ru",12:"strings/ro",13:"strings/pt",14:"strings/pl",15:"strings/pa",16:"strings/nl-NL",17:"strings/ko",18:"strings/ja",19:"strings/it",20:"strings/id",21:"strings/hu",22:"strings/hi",23:"strings/fr",24:"strings/es",25:"strings/en",26:"strings/el",27:"strings/de",28:"strings/cs",29:"strings/bn",30:"strings/ar"}[r]||r)+"-"+{0:"2b9feda7",1:"662ee5e7",2:"c444b0a9",3:"a5658bf8",4:"3ea447d8",5:"1573893a",6:"c32ed883",7:"52cac8bc",8:"2c58adbb",9:"681aaba6",10:"d05b78c6",11:"f4071afb",12:"a1349f5c",13:"6a57ec9f",14:"762dfc94",15:"8a02897a",16:"4e429b1e",17:"8e921ddf",18:"524cc86b",19:"8df42324",20:"7d8a8fc5",21:"4fde5d79",22:"509b8809",23:"9f09bcfb",24:"77da48d4",25:"44cfb321",26:"13b268cc",27:"c0cac402",28:"3ecdeec1",29:"dfd2b224",30:"074ffddd"}[r]+".js";var a=setTimeout(t,12e4);return c.onerror=c.onload=t,o.appendChild(c),i},n.m=r,n.c=e,n.d=function(r,t,e){n.o(r,t)||Object.defineProperty(r,t,{configurable:!1,enumerable:!0,get:e})},n.n=function(r){var t=r&&r.__esModule?function(){return r.default}:function(){return r};return n.d(t,"a",t),t},n.o=function(r,n){return Object.prototype.hasOwnProperty.call(r,n)},n.p="/",n.oe=function(r){throw console.error(r),r}}([])</script><script src="//d35aaqx5ub95lt.cloudfront.net/js/vendor-2b9feda7.js"></script>                       <script src="//d35aaqx5ub95lt.cloudfront.net/strings/en-44cfb321.js"></script>     <script src="//d35aaqx5ub95lt.cloudfront.net/js/app-662ee5e7.js"></script></body></html>

as you can see the JSON is wrapped inside a HTML page which is not valid JSON syntax it something related to the API itself. 如您所见,JSON被包装在无效的JSON语法HTML页面中,它与API本身有关。 it returns a page instead of JSON object . 它返回一个页面而不是JSON对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM