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);
%>