API JSON 回调问题

API JSON callback issue

本文关键字:问题 回调 JSON API      更新时间:2023-09-26

>我有一个简单的输入字段,当你使用 Trakt API 搜索它们时,它会返回节目。最近他们更改了他们的 API,现在我的代码不再有效(以前)。我遇到这个问题:

Refused to execute script from http://.... because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

法典:

  $.ajax ({
    type: "GET",
    // **OBSOLETE** url: 'http://api.trakt.tv/search/shows.json/78c0761c9409a61cf88e675687d6f790/'+ value +'/5/seasons/',
    url: 'http://api.trakt.tv/search/shows.json/78c0761c9409a61cf88e675687d6f790?query=' + value + '&limit=5&seasons=true',
    dataType: "jsonp",
    json: "callbackname",
    crossDomain : true,

如果我删除:

dataType: "jsonp",

或更改为:

dataType: "json",

我收到不同的错误:

XMLHttpRequest cannot load http://.... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://dl.dropboxusercontent.com' is therefore not allowed access.

演示:http://dl.dropboxusercontent.com/u/48552248/websites/tiii.me/index.html(如果强制 https://则"加载不安全脚本")

代码链接:https://dl.dropboxusercontent.com/u/48552248/websites/tiii.me/scripts/partials/_tv-show.js

有什么想法吗?谢谢!

试试这个

function getJSONP(url, success) {
    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;
    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };
    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);
}

看起来您得到的响应不是 jsonp 响应,而是 json 响应。在jsonp中,你应该得到一个javascript方法回调。而在您的情况下,它是纯 json 数据。因此,您需要处理 JSON 数据并手动调用 callbackname 方法,并将要返回的对象作为 JSON 结果传递。