2015-04-16 128 views
1

我创建safari扩展,我在这个扩展中注入js。在这个JS代码中,我发送ajax调用,在控制台中创建以下错误。 “请求头域X-Requested-With不允许通过访问控制允许头” 这里是我的代码:需要帮助来解决Ajax问题?

这个函数我从网上复制来解决跨域问题,但它不工作请帮我弄清楚这一点。

function createCORSRequest(method, url) { 

    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr) { 
     // XHR has 'withCredentials' property only if it supports CORS 
     xhr.open(method, url, true); 
    } else if (typeof XDomainRequest != "undefined") { // if IE use XDR 
     xhr = new XDomainRequest(); 
     xhr.open(method, url); 
    } else { 
     xhr = null; 
    } 
    return xhr; 
} 


var request = createCORSRequest("get", "https://www.karmora.com/list.xml"); 

if (request) { 
    // Define a callback function 
    request.onload = function() { 
}; 
    // Send request 
    request.send(); 
} 

$.get('https://example.com', function (data) { 
    alert("Ajax call successfull"); 
}); 

回答

1

你的问题与Same-origin_policy

相关。如果你有机会到服务器,添加到Apache Web服务器的虚拟主机配置以下设置:

Header set Access-Control-Allow-Origin "*" 
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept" 
+1

我在Chrome扩展使用相同的代码它的工作正常。错误只是在Safari浏览器。 –