跨域Ajax调用 [英] Cross-Domain AJAX Call

查看:123
本文介绍了跨域Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图与最新的jQuery跨域AJAX调用的Twitch.TV API和我得到一个错误。

code:

  $。阿贾克斯({
    键入:GET,
    数据类型:JSON,
    网址:https://api.twitch.tv/kraken/search/games?q=star&type=suggest
    成功:函数(responseData,textStatus,jqXHR){
        的console.log(中);
        VAR数据= JSON.parse(responseData ['AuthenticateUserResult']);
        的console.log(数据);
    },
    错误:函数(responseData,textStatus,errorThrown){
        警报(POST失败。');
    }
});
 

错误:

  

XMLHtt prequest无法加载 https://开头API ?.twitch.tv /海妖/搜索/游戏Q =明星和放大器;类型=建议的。没有访问控制 - 允许 - 原产地标头的请求的资源present。原产地 HTTP://$c$ceplus.net '。因此不会允许访问

解决方案

您需要JSONP跨浏览器的请求。你给我的链接工作正常的getJSON jQuery函数。

对于流: http://jsfiddle.net/82wNq/27/

游戏 http://jsfiddle.net/82wNq/25/

<$p$p><$c$c>$.getJSON("https://api.twitch.tv/kraken/search/games?q=star&type=suggest&callback=?",功能(数据){     $每个(data.games,函数(指数,项目){         $(&LT; D​​IV&gt;中)。HTML(item.name).appendTo(#内容);         $(&LT; IMG&gt;中)ATTR(src用户,item.box.medium).appendTo(#内容)。     }); });

I am trying to make a cross-domain AJAX call with the latest jQuery for the Twitch.TV API and I'm getting an error.

Code:

 $.ajax({
    type: 'GET',
    dataType: "json",
    url: "https://api.twitch.tv/kraken/search/games?q=star&type=suggest",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
        var data = JSON.parse(responseData['AuthenticateUserResult']);
        console.log(data);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

Error:

XMLHttpRequest cannot load https://api.twitch.tv/kraken/search/games?q=star&type=suggest. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://codeeplus.net' is therefore not allowed access.

解决方案

You need JSONP for cross-browser requests. The link you gave me works fine with getJSON jquery function.

for streams: http://jsfiddle.net/82wNq/27/

for games: http://jsfiddle.net/82wNq/25/

$.getJSON("https://api.twitch.tv/kraken/search/games?q=star&type=suggest&callback=?", function (data) {
    $.each(data.games, function (index, item) {
        $("<div>").html(item.name).appendTo("#content");
        $("<img>").attr("src", item.box.medium).appendTo("#content");
    });
});

这篇关于跨域Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆