我有两个不同的java web项目在两个不同tomcat服务器上运行。比方说projA和projB在这里,我试图从projA加载projB中可用的html。我只是简单地使用jQuery.load()来实现这一点。但它在请求的资源错误中没有"Access Control Allow Origin"标头。我还尝试在这里使用jquery跨域插件https://github.com/padolsey-archive/jquery.fn/tree/master/cross-domain-ajax
但这并不奏效。任何帮助都将不胜感激。
代码我正在尝试
$191('.ontop').load("http://"+host+":8080/OtherDomain/",function(response,status)
{
if (status == "error")
{
$191('.ontop').empty();
var msg = "Sorry We could not connect to our server.. Please try again later.";
alert(msg);
}
else
{
alert(status);
$191('.ontop').css('display', 'block');
}
});
您可能需要使用代理服务器进行请求。
我找到了Here并制作了这把小提琴http://jsfiddle.net/2kn52u3s/1
代码片段-
设置ajax头-
$.ajaxSetup({
scriptCharset: "utf-8", //maybe "ISO-8859-1"
contentType: "application/json; charset=utf-8"
});
然后以-的形式请求跨域JSON请求
$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent('http://google.com') + '&callback=?',
function(data) {
$("#target").html(data.contents);
});
所以这里是我得到的CORS错误的答案:
我在web.xml 中添加了以下过滤器
<filter>
<filter-name>myResponseFilter</filter-name>
<filter-class>com.filters.ResponseHeaderFilter</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>myResponseFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
然后有一个自定义的过滤器写入设置标题:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
String origin = httpRequest.getHeader("origin");
origin = (origin == null) ? "*" : origin;
httpResp.setHeader("Access-Control-Allow-Origin", origin);
httpResp.setHeader("Access-Control-Allow-Methods", "GET, POST");
httpResp.setHeader("Access-Control-Allow-Credentials", "true");
httpResp.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
httpResp.setHeader("Access-Control-Max-Age", "86400");
filterChain.doFilter(request, response);
}