jquery1.4 ajax跨域访问

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">      
<html>      
  <head> 
      <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">      
      <meta http-equiv="description" content="this is my page">      
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">   

<script type="text/javascript" src="js/jquery/jquery.js"  ></script>      
     
        <script type="text/javascript">         
            function test(){      
                $.getJSON("http://server.yondor5.com:8080/remoteLogin/RequestIsLogin.jsp?Math.random()*100+1&callback=?",      
               function(data){   
                         alert(data); 
                          if(data.result=="OK"){ 
                            alert('OK'); 
                          }else{ 
                          alert('ERROR'); 
                          } 
                });               
            }      
                   
                  
        </script> 
        
  </head> 
  
  <body> 
          <% 
String username = (String)request.getSession().getAttribute("yondor.currentPassport"); 
       
if(username!=null && username.length()>0){ 
out.println("hi.welcome to our home "+username); 
%>   
<% 
}else 
{ 
%> 

<% 
} 
%> 
   <input type="button" value="跨域" id="test" onclick="test()"/>  
<div id="images">   
        </div>   
  </body> 
</html> 

访问页面index.jsp 

 

 

 

被访问页面RequestIsLogin.jsp

<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>
<%@ page import="com.yondor.LoginInfo" %>
<%
//判断在其他域名下是否登录

String callback = request.getParameter("callback"); 

  response.getWriter().print(callback+"({'result':'OK'})"); 
 %>
 
 <%
}
%>

 

 

Ajax的应用中,由于安全的问题,浏览器默认是不支持跨域调用的。传统解决的方法,包括:(参考http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/)

Local proxy:
Needs infrastructure (can't run a serverless client) and you get double-taxed on bandwidth and latency (remote - proxy - client).
Flash:
Remote host needs to deploy a crossdomain.xml file, Flash is relatively proprietary and opaque to use, requires learning a one-off moving target programming langage.
Script tag:
Difficult to know when the content is available, no standard methodology, can be considered a "security risk".

以上方法都各有缺陷,都不是很好多解决方案。后来出现了一种叫JSON with Padding 的技术,简称 JSONP .(原理参考http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/),应用JSONP可以实现JSON数据的跨域调用。非常的幸运,JQuery1.2以后支持JSONP的应用。下面侧重说明在JQuery中,Json的跨域调用。

      应用JSONP实现Json数据跨域调用,需要服务器端与客户端的合作完成。引用Jquery官方的例子,客户端掉用如下:

 

总结,用JSONP要做两件事:

      1/请求地址加参数:jsoncallback=?

      2/服务器段把jsoncallback的值作为方法名传回来,如JQUET098788(...) 

你可能感兴趣的:(html,Ajax,jsp,json)