如何使用jQuery加载跨域html [英] How to load cross domain html using jQuery

查看:377
本文介绍了如何使用jQuery加载跨域html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个不同的java web项目在2个不同的tomcat服务器上运行。
可以说projA和projB
在这里,我试图从projA加载projB中的html。我简单地使用jQuery.load()来实现这一点。但它给了我没有'访问控制 - 允许 - 来源'标题出现在请求的资源错误。我也尝试在这里使用jQuery跨域插件 https: //github.com/padolsey-archive/jquery.fn/tree/master/cross-domain-ajax

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.

代码我正在尝试

$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');
    }
});


推荐答案

我在web.xml中添加了以下过滤器:

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);
    }

这篇关于如何使用jQuery加载跨域html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆