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

使用jsonp实现ajax跨域访问
    工作中的一个巧合,提到了ajax跨域访问的问题,刚刚心血来潮,弄了个简单的例子,为便于记忆,将前端和后端代码简单贴下:
    前端:

<%@ page language="java" contentType="text/html; charset=UTF-8"%>     
<html>
<head>     
<title>ajax jsonp test</title>
<script src="jquery/jquery-1.3.2.min.js" type="text/javascript">     
</script>      
<script type="text/javascript">    
$(document).ready(function(){    
   $("#button").click(function(){      
       $.ajax({   
          data:"?callback=?",
          url: 'http://192.168.1.170/resp.jsp',
          dataType:'jsonp',
          success:function(json){ 
             $("#show").html(json); 
          }
        });   
     });
 });     
</script>      
</head>     
<body>     
<form id="form1" name="form1" method="post">  
<INPUT TYPE="button" value="提交" id="button"/>     
</form>     
<div id="show"> 
</div>     
</body>     
</html>    

   后端:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
         String callback = request.getParameter("callback");
         String resp = "\"helloworld!\"";
         out.print(callback+"("+resp+")");
%>