阿贾克斯 - "访问控制允许来源"错误 [英] Ajax - "Access-Control-Allow-Origin" Error

查看:104
本文介绍了阿贾克斯 - "访问控制允许来源"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图与即时串流API ,查看工作某个频道上线,但不断收到此错误:

  XMLHtt prequest无法加载http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft。原产地http://www.webdevstl.com没有被访问控制允许来源允许的。

我需要通过PHP来运行它,还是我做错了什么在我的Ajax调用?这是pretty直截了当code:

 函数getActive(){
    如果(window.XMLHtt prequest)
    {
        XMLHTTP =新XMLHtt prequest();
    }
    其他
    {
        XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);
    }    xmlhttp.onreadystatechange =功能()
    {
        如果(xmlhttp.readyState == 4和&放大器; xmlhttp.status == 200)
        {
            VAR JSON = JSON.parse(xmlhttp.responseText);
            的console.log(JSON);
        }
    }    xmlhttp.open(GET,http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft,真正的);
    xmlhttp.setRequestHeader(内容类型,应用程序/ x-WWW的形式urlen codeD);
    xmlhttp.send();
}
getActive();


解决方案

您正在运行到由的同源策略。总之,AJAX调用到不同的域被禁止,将失败 - 除非远程主机明确允许

您必须要么使用JSONP(主要是适用于通过API的返回数据)或代理通过自己的服务器/域请求。

CORS也将是一种选择,但假设你能够访问远程服务器的配置。

I'm trying to work with the Livestream API to see if a certain channel is live but keep getting this error:

XMLHttpRequest cannot load http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft. Origin http://www.webdevstl.com is not allowed by Access-Control-Allow-Origin.

Do I need to run it through PHP or am I doing something wrong in my ajax call? It's pretty straight forward code:

function getActive(){
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {   
            var json = JSON.parse(xmlhttp.responseText);
            console.log(json);
        }
    }

    xmlhttp.open("GET", "http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send();
}
getActive();

解决方案

You're running into restrictions imposed by the Same Origin Policy. In short, AJAX calls to a different domain are prohibited and will fail - unless explicitly permitted by the remote host.

You need to either use JSONP (mostly applicable to data returned by APIs) or proxy the request through your own server/domain.

CORS would also be an option, but that assumes you having access to the remote server's config.

这篇关于阿贾克斯 - "访问控制允许来源"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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