问题
I have 2 different java web projects running on 2 different tomcat server. Lets say projA and projB Here I am trying to load html available in projB from projA. I am simply using jQuery.load() to achieve this.But it is giving me No 'Access-Control-Allow-Origin' header is present on the requested resource error. I also tried to use jquery cross domain plugin availabele here https://github.com/padolsey-archive/jquery.fn/tree/master/cross-domain-ajax
But this does not work out. Any help will be appreciated.
code i am trying
$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');
}
});
回答1:
You may want to use a proxy server to request it.
I found Here and made this fiddle- http://jsfiddle.net/2kn52u3s/1
code snippet-
setup ajax headers-
$.ajaxSetup({
scriptCharset: "utf-8", //maybe "ISO-8859-1"
contentType: "application/json; charset=utf-8"
});
And then request a cross domain JSON Request as-
$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent('http://google.com') + '&callback=?',
function(data) {
$("#target").html(data.contents);
});
回答2:
So here is the answer for CORS error i am getting:
I added following filter in my 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>
and then there is a custom Filter written to set headers:
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);
}
来源:https://stackoverflow.com/questions/29360797/how-to-load-cross-domain-html-using-jquery