如何使用 jQuery 加载跨域 html

How to load cross domain html using jQuery

我在 2 个不同的 tomcat 服务器上有 2 个不同的 java Web 项目 运行。 让我们说 projA 和 projB 在这里,我试图从 projA 加载 projB 中可用的 html。我只是使用 jQuery.load() 来实现 this.But 它给我 No 'Access-Control-Allow-Origin' header is present on the requested resource 错误。我还尝试在此处使用 jquery 可用的跨域插件 https://github.com/padolsey-archive/jquery.fn/tree/master/cross-domain-ajax

但这行不通。 任何帮助将不胜感激。

我正在尝试的代码

1('.ontop').load("http://"+host+":8080/OtherDomain/",function(response,status) 
{

    if (status == "error") 
    {
        1('.ontop').empty();
        var msg = "Sorry We could not connect to our server.. Please try again later.";
        alert(msg);
    }
    else
    {
        alert(status);
        1('.ontop').css('display', 'block');
    }
});

您可能需要使用代理服务器来请求它。

我找到了Here and made this fiddle- http://jsfiddle.net/2kn52u3s/1

代码片段-

设置ajaxheaders-

$.ajaxSetup({
    scriptCharset: "utf-8", //maybe "ISO-8859-1"
    contentType: "application/json; charset=utf-8"
});

然后请求跨域JSON请求as-

$.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>

然后有一个自定义过滤器写入设置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);
    }