加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

JSONP跨域实例

发布时间:2020-12-16 19:46:18 所属栏目:百科 来源:网络整理
导读:Server端: Eclipse新建动态web项目JsonpServer,并将相应的tomcat端口号都加1(避免和另一个MyEclipse项目冲突),变成如下: 图1 新建servlet:JsonpServlet,核心代码如下: protected void doGet(HttpServletRequest request,HttpServletResponse respons
Server端: 
 

Eclipse新建动态web项目JsonpServer,并将相应的tomcat端口号都加1(避免和另一个MyEclipse项目冲突),变成如下:

图1

新建servlet:JsonpServlet,核心代码如下:

 
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/javascript");
		PrintWriter out = response.getWriter();
		String callback = request.getParameter("callback");
		out.print(callback
				+ "([ { name:'John',age:'19'},{ name:'joe',age:'20'}])");
		System.out.println("callback = " + callback);
		out.flush();
		out.close();
	}

注意setContentType的值为text/javascript,

启动tomcat,访问http://localhost:8081/JsonpServer/JsonpServlet,得到结果:


图2

=====================================================================

Client端:

新建web项目JsonpCilent,在index.jsp页面中书写javascript代码,一共三种方式(自己总结的),

代码如下:(不要忘记引入JQuery.js文件)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
    <script src="jsFiles/jQuery-1.8.3-min.js" type="text/javascript"></script>
    <!-- 第一种:JS代码书写方式
    <script type="text/javascript">  
    function jsonpCallback(result){   
       alert(result[1].name);   
    }   
    </script>
    <script type="text/javascript"src="http://localhost:8081/JsonpServer/JsonpServlet?callback=jsonpCallback"></script>
    -->
    <!-- 第二种:Jquery简单代码书写方式
    <script type="text/javascript">   
    $.getJSON("http://localhost:8081/JsonpServer/JsonpServlet?callback=?",function(json){    
        alert(json[0].name);   
    });
    </script>
    -->
    <!-- 第三种:Jquery完全代码书写方式  -->
    <script type="text/javascript">
           $.ajax({
            url:"http://localhost:8081/JsonpServer/JsonpServlet",dataType:"jsonp",jsonp:"callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback),需和服务器端一致
            jsonpCallback:"person",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
            success:function(json){
                //alert(json[0].name);
            }
           });
           // 相当于重写success后执行的函数(自定义为person)
           function person(json){
               alert("I am person function...");
               alert(json[0].name);
           }
    </script>
  </head>
 
  <body>
  </body>
</html>




我们使用第三种方式,启动tomcat,访问http://localhost:8080/JsonpClient/

图3


确定后

图4

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读