我在2个不同的tomcat服务器上运行了2个不同的java web项目。 让我们说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');
}
});
答案 0 :(得分:0)
您可能希望使用代理服务器来请求它。
我找到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);
});
答案 1 :(得分:0)
所以这是我得到的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>
然后有一个自定义Filter写入设置标题:
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);
}