ajax跨域访问的解决方案

  今天的工作中要访问摄像机内部的一个web站点,这就涉及到jquery的ajax跨域访问的问题。我使用的是jquery1.7的版本,下面总结如下:

  • 问题一:
    一开始用IE调试,总是返回No Transport错误,这是因为在进行跨域访问的时候,IE8浏览器(不同的浏览器对跨域的支持不一样)不支持跨域访问,必须在ajax请求前面加上 jQuery.support.cors = true;才行。

  • 问题二:跨域问题解决后,返回的xhr.statusText = "[object Error]",并且xmlHttpReqest.readyState始终为0。
    后来我更改为自己的url,可以访问,说明是跨域的问题。后来我不用jquery的ajax,用最原始的ajax在执行到open函数的时候,提示没有权限。这才知道是跨域访问没有权限的问题。

  后来在项目组同事的帮助下找到了下面的解决方案:

  就是通过吧url和参数发送给servlet,然后servlet再建立HttpURLConnection,把请求发送给其他的站点。当然我们的项目为了把所有发送的请求都对应一个servlet,使用的是过滤器。

  first.jsp:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>   
    <link href="IEfile/doc/css/base.css" rel="stylesheet" type="text/css" />
    <link href="IEfile/doc/css/login.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="IEfile/doc/script/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="IEfile/doc/script/jquery.cookie.js"></script>
    <script type="text/javascript" src="IEfile/doc/script/login.js"></script>
    <script type="text/javascript" src="IEfile/doc/script/common.js"></script>
    <script type="text/javascript" src="IEfile/doc/script/Translator.js"></script>
    
    <script type="text/javascript">
    var g_lxdLogin = null; // Login.xml
      function DoLogin()                            
      { 
          m_szUserPwdValue = "111";//Base64.encode("admin" + ":" + "12345");
          var m_lHttp = "http://";
          var m_szHostName = "localhost";
          var m_lHttpPort = "8080";
          var urlTest = m_lHttp + m_szHostName + ":" + m_lHttpPort + "/WebServerTest1/PSIA/Custom/SelfExt/userCheck";
          alert(urlTest);
          $.ajax({
              type: "GET",
              url: urlTest,
              async: true,
              timeout: 15000,
              beforeSend: function(xhr) {
                  xhr.setRequestHeader("If-Modified-Since", "0");
                  xhr.setRequestHeader("Authorization", "Basic " + m_szUserPwdValue);
              },
              success: function(xmlDoc, textStatus, xhr) 
              {
                alert("login success");
                  if("200" == xmlDoc.documentElement.getElementsByTagName('statusValue')[0].childNodes[0].nodeValue)
                  {
                      var szUrl = decodeURI(document.URL);
                      if(szUrl.indexOf("?page=") != -1)
                      {
                          var szPage = szUrl.substring(szUrl.indexOf("page=") + 5, szUrl.indexOf("&params="));
                          if(szPage.indexOf(".asp") == -1)
                          {
                              szPage = szPage.concat(".asp");
                          }
                          var szParam = szUrl.substring(szUrl.indexOf("&params=") + 8, szUrl.length);
                          $.cookie('page',szPage+"?"+szParam+"%1");
                      }
                      else
                      {
                          $.cookie('page',null);
                      }
                      
                      $.cookie('userInfo'+m_lHttpPort,m_szUserPwdValue==""?Base64.encode("anonymous:\177\177\177\177\177\177"):m_szUserPwdValue);
                      window.location.href = "main.asp";
                  }
                  else
                  {   
                      if(!$('#UserName').prop("disabled")) {
                          $('#UserName').focus();
                      }
                      $('#UserName').val('');
                      $('#Password').val('');
                      alert(translator.translateNode(g_lxdLogin, 'LoginTips4'));
                  }
              },
              error: function(xhr, textStatus, errorThrown)
              {
                alert("login error = " + textStatus);
                  if("timeout" == textStatus)
                  {
                      alert(translator.translateNode(g_lxdLogin, 'ConnectTimeoutTips'));
                  }
                  else
                  {
                      alert(translator.translateNode(g_lxdLogin, 'NetworkErrorTips'));
                  }
              }
          });
      }    
    </script>  
  </head>  
    
  <body >  
    <input type="button" name="b" value="TestJson" onclick="DoLogin()"/>    
  </body>  

</html>

 


  web.xml:

    <!-- psia过滤器 -->
    <filter>
        <filter-name>psiaFilter</filter-name>
        <filter-class>com.zm.servlet.psiaFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>psiaFilter</filter-name>
        <url-pattern>/PSIA/*</url-pattern>
    </filter-mapping>
        
    <!-- 起始页面-->
  <welcome-file-list>
    <welcome-file>/IEfile/doc/page/first.jsp</welcome-file>
  </welcome-file-list>
  

 

  psiaFilter.java:  

package com.zm.servlet; 

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.*;
import javax.servlet.http.*;

public class psiaFilter implements javax.servlet.Filter {

        public void destroy() {
        }

        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            
            HttpServletRequest req = (HttpServletRequest)(request); 
            String uri = req.getRequestURI();
            uri = uri.substring(15);
            String Auth = req.getHeader("Authorization");
            String method = req.getMethod();
            HttpServletResponse res = (HttpServletResponse)(response);
            
            //((HttpServletResponse)(response)).sendError(700, "psiaFilter" + uri + Auth);
            
            String url= "http://172.16.8.178" + uri;          
            URL theURL = new URL(url);              
            HttpURLConnection urlConnection = (HttpURLConnection)theURL.openConnection();
             
            urlConnection.setReadTimeout(11);
            urlConnection.setRequestMethod(method);
            urlConnection.setRequestProperty("If-Modified-Since", "0");
            urlConnection.setRequestProperty("Authorization", Auth);
            urlConnection.connect();  
              
            PrintWriter out = res.getWriter();
            //out.println(url);
              
            InputStream in = urlConnection.getInputStream();
            int c;
            while((c = in.read()) != -1)
                out.write(c);
            System.out.println(out.toString());
            //chain.doFilter(request, response);
        }

        public void init(FilterConfig arg0) throws ServletException {
        }

    }

 

posted @ 2013-12-31 16:35  matthew2015  阅读(1343)  评论(0编辑  收藏  举报