index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
//String path = request.getContextPath();
//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<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">
<script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url:'http://172.16.1.53:8080/jsonp/getData.jsp',
dataType:"jsonp",
jsonp:"jsonpcallback",
success:function(data){
var $ul = $("<ul></ul>");
$.each(data,function(i,v){
$("<li/>").text(v["id"] + " " + v["name"]).appendTo($ul)
});
$("#res").append($ul);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert("连接失败\nXMLHttpRequest="+XMLHttpRequest.statusText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
}
});
});
</script>
</head>
<body>
<div id="res"></div>
<!--
说明:
客户端(url:http://192.168.1.2:8080/jsonp/index.jsp)
客户端页面 body 中放置一个div: <div id="res"></div> ,准备将远程调用的数据写入该div中。
服务端(url:http://192.168.1.3:8080/jsonp2/getData.jsp)
代码很简单,就是输出一个字符串,
正常输出 json 应该是:[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}] ,
jsonp 则输出: jsonpcallback([{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]) 其中“jsonpcallback”是客户端传过来的。
-->
</body>
</html>
getData.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String jsonp = request.getParameter("jsonpcallback");
String str = "[{\"id\":\"1\",\"name\":\"测试1\"},{\"id\":\"2\",\"name\":\"测试2\"}]";
str = jsonp + "(" +str+")";
response.getWriter().write(str);
%>
本文介绍了如何在JSP页面中利用JSONP技术从远程服务器获取并展示数据,通过引入jQuery库进行AJAX请求,实现了动态加载数据的功能。文章详细解释了JSONP的工作原理,并提供了示例代码,包括index.jsp和getData.jsp两个关键页面的代码解析。
309

被折叠的 条评论
为什么被折叠?



