日期:2014-05-16  浏览次数:20468 次

使用JSONP 处理跨域请求

注:为了解决实际项目中因跨域访问js问题而写的有关jsonp的Demo,记录如下。

?

一、相关定义。

JSONP(JSON with Padding):JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)。?

?

二、JSONP由何演化。

?

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jsonp的使用</title>

<script type="text/javascript">
function showPrice(data) {
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
}
</script>
<script type="text/javascript">
showPrice({symbol: 'IBM', price: 91.42});
</script>
</head>
<body>

</body>
</html>

?

三、JSONP的简单使用

?

hellojsonp.jsp 如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jsonp的用法</title>

 <script type="text/javascript">  
        function jsonpCallback(result)   
           {   
             alert(result.msg);   
           }   
       </script>  
<script type="text/javascript" src="http://192.168.11.139:8081/MyWeb/HelloJsonp?jsonp=jsonpCallback"></script>  
</head>
<body>

</body>
</html>

?后台?HelloJsonp.java ?相关代码?如下:

?

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
  String jsonData = "{msg:'hello jsonp,haha'}";
  String output = "jsonpCallback" + "(" + jsonData + ");";
  response.setCharacterEncoding("UTF-8");
  response.setContentType("text/javascript");          
  PrintWriter out = response.getWriter();
    System.out.println(output);
  out.println(output);  
 }

?

四、Jquery 对Jsonp的支持。

?

jsonpinjquery.jsp 如下:

?

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSONP IN  JQUERY</title>

<script src="<%=basePath%>js/jquery-1.4.4.js"></script>

<script type="text/javascript">

jQuery.getJSON("http://192.168.11.139:8081/MyWeb/TestJson?callback=?", 
function(data) {
    alert("symbol:"+data.symbo