【问题标题】:API JSON callback issueAPI JSON 回调问题
【发布时间】:2015-03-02 16:57:45
【问题描述】:

我有一个简单的输入字段,可以在您搜索节目时返回节目,使用 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

有什么想法吗?谢谢!

【问题讨论】:

  • API 服务 JSON 并不意味着它启用了 CORS 或它将服务 jsonp。阅读 API 文档,如果这两种方法都不可用,请使用代理。
  • 尝试正确设置选项。阅读 ajax 文档
  • 您甚至可以使用 php 创建自己的代理,并在您方便时返回 json 或 jsonp

标签: javascript jquery json api jsonp


【解决方案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);

}

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 如果我改成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.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多