我已经阅读了有关AJAX / JSONP的几篇帖子,我可以从Yahoo!成功检索JSONP数据通过在localhost上提供的页面中的AJAX调用API,但我无法从localhost上的Cocoon获取数据。
我在本地主机:80上有Apache提供的网页。该页面包含AJAX代码,用于从localhost获取一些JSONP:8080 / cocoon / test /
当我直接加载localhost:8080 / cocoon / test /时,我得到了预期的数据:
{"titles":[
{"title":"Title 1"},
{"title":"Title 2"},
... ,
{"title":"Title 999"}
]}
但是当我执行以下内容时:
function getTitles() {
var url = "http://localhost:8080/cocoon/test/";
$.getJSON(url, function(response) {
console.log(JSON.stringify(response));
});
}
我明白了:
"阻止跨源请求:同源策略禁止在localhost:8080 / cocoon / test /读取远程资源。这可以通过将资源移动到同一域或启用CORS来解决。"
有谁知道为什么上面的AJAX代码适用于Yahoo! url(下面),但没有localhost上的cocoon?
感谢您对此有任何想法/指导。
答案 0 :(得分:0)
花了一段时间,但我解决了CORS问题。
如果您从Apache HTTP Server提供服务,请将以下内容添加到您的httpd.conf文件中:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
如果您从Tomcat提供服务,请将以下内容添加到您的web.xml文件中:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>