ajax实现跨域访问的问题

本文介绍了一种通过后台代理实现的跨域请求解决方案。利用Ext.Ajax进行前台请求,并通过后台代理action来完成跨域访问。文章详细展示了如何配置前端请求及后台处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里主要解决ajax跨全域的问题,而且主要使用后台代理的方式实现。

前台ajax处理:

  Ext.Ajax.request({ 
                           url : '×××.action'    //后台代理action
                           callback: function(options,success,response){

                          }

     });

后台代理action

          /**
         * 代理前台进行跨域访问
         * @throws Exception
         */
        public void domainProxy() throws Exception{
            // 变量初始化
            HttpServletRequest request = ServletActionContext.getRequest();
            String url = "www.baidu.com" ;     //http请求地址,即需要跨域进行访问的地址,例如“www.baidu.com”
            String str = executeGet(url);            //发送请求,跨域访问
            JsonUtil.OutJsonString(str) ;   //以json形式,返回ajax请求数据
        }
       

后台http发送请求函数(参考http://ipfire.iteye.com/blog/978063)
        /**
         * 使用HttpClient获取HttpGet请求
         * @throws Exception
         */
        @SuppressWarnings("finally")
        public String executeGet(String url) throws Exception {  
            BufferedReader in = null;  
            String content = null;  
            try {  
                // 定义HttpClient  
                HttpClient client = new DefaultHttpClient();  
                // 实例化HTTP方法  
                HttpGet request = new HttpGet();  
                request.setURI(new URI(url));  
                HttpResponse response = client.execute(request);  

                in = new BufferedReader(new InputStreamReader(response.getEntity()  
                        .getContent(),"utf-8"));    //解决中文乱码问题

                StringBuffer sb = new StringBuffer("");  
                String line = "";  
                String NL = System.getProperty("line.separator");  
                while ((line = in.readLine()) != null) {  
                    sb.append(line + NL);  
                }  
                in.close();  
                content = sb.toString();  
            } finally {  
                if (in != null) {  
                    try {  
                        in.close();// 最后要关闭BufferedReader  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
                return content;  
            }  
        }  


        此处http请求用到了jar包,注意引入commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar。下载地址:http://www.eu.apache.org/dist/httpcomponents/httpclient/binary/


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值