ajax 跨域异步调用

涉及到跨域调用时,一般的js ,得不到应有的数据。必须通过UrlConnection来获取到字节数据,来显示出来

思路:当前项目下的js调用到一个jsP,在这个jsp上通过urlConnect 链接来获取数据,并根据状态,回写到所要的js调用之处。

function getText(depart){
 var url="/.././*.jsp?depart="+depart;
 xreq = createXmlHttpRequest();
 if (!xreq){
  alert('Giving up :( Cannot create an XMLHTTP instance');
  return false;
 }
 var url=url+"&temptime="+Math.random();
 xreq.onreadystatechange = showInfo; 
 xreq.open('GET', url, true);
 xreq.send(null);
}
function showArticleInfo(){
 if (xreq.readyState == 4){
  if (xreq.status == 200){
   var articleInfo= xreq.responseText;

//业务处理
    var artId=artInfoArr[0];
    var artTitle=artInfoArr[1];
    var openArticleUrl="/.././*.jsp?art_bh="+artId;
    window.open(openArticleUrl,"newwindow","width=500,height=200,scrollbars=yes,resizable=yes");
   }   
  }
  else if(xreq.status== 500){
   alert('ERRO'+xreq.responseText);
  }
 }
}

 

jsp   //跨域得到数据

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<%
 String depart = request.getParameter("depart");
 String retArtInfo = "";
 if (!(depart == null || depart.trim().equals(""))) {

  String url = "http://外网地址/项目名/*.do?method=*&depart="+depart+"&tamp="+ new Date().getTime();

//方法返回的是串
  URL U = new URL(url);
  String result = "";
  try {
   URLConnection connection = U.openConnection();
   connection.connect();
   BufferedReader in = new BufferedReader(
     new InputStreamReader(connection.getInputStream()));

   String line;

   while ((line = in.readLine()) != null) {
    result += line;
   }
   retArtInfo=result;
   in.close();
   out.clear();
  } catch (Exception e) {

  }

 }
 out.println(retArtInfo);
%>

 

你可能感兴趣的:(Ajax)