API JSON回调问题

时间:2015-01-05 06:53:49

标签: javascript jquery json api jsonp

我有一个简单的输入字段,可以在使用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.

CODE:

  $.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

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:1)

尝试这个

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);

}

答案 1 :(得分:-2)

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