1 <%@ page pageEncoding="utf-8 contentTypetext/html;charset=UTF-8 languagejava" %>
2 <html>
3 head 4 title>跨域测试</ 5 script src="js/jquery-1.7.2.js"></script 6 7 $(document).ready(function () {
8
9 $(#btn).click(10 $.ajax({
11 url: 'http://localhost:9090/student,12 type: GET13 success: (data) {
14 $(text).val(data);
15 }
16 });
17
18 });
19
20 });
21 22 23 body24 input id="btn" type="button" value="跨域获取数据" />
25 textarea ="text" style="width: 400px; height: 100px;"textarea26 27 >
7 //回调函数
8 showData (result) {
9 var data JSON.stringify(result); json对象转成字符串
#text).val(data);
}
12
14
16 向头部输入一个脚本,该脚本发起一个跨域请求
17 $(head).append(<script src='http://localhost:9090/student?callback=showData'><\/script>);
19
26
28 >
1 protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
2 response.setCharacterEncoding("UTF-8" 3 response.setContentType("text/html;charset=UTF-8" 4
//数据
6 List<Student> studentList = getStudentList();
7
8
9 JSONArray jsonArray = JSONArray.fromObject(studentList);
10 String result = jsonArray.toString();
11
12 前端传过来的回调函数名称
13 String callback = request.getParameter("callback"14 用回调函数名称包裹返回数据,这样,返回数据就作为回调函数的参数传回去了
15 result = callback + "(" + result + ")";
16
17 response.getWriter().write(result);
18 }
8 9
dataType: jsonp指定服务器返回的数据类型
17 result JSON.stringify(data); $().val(result);
19 21
22 23
24 28 29 30
31 32 >
showData (data) {
console.info(调用showData10
11 JSON.stringify(data);
window.showData = function (data) {
console.info("调用showData");
//
var result = JSON.stringify(data);
21 $("#text").val(result);
}
25
26 27 28 29 30 jsonpCallback: showData"指定回调函数名称
31 32 console.info(调用success33 34 35 36
37 38 39 40 41 42 43
44 45 >
18
23 jsonp: theFunction指定参数名称
25 32 33 34 35 36 37
38 >
13 String callback = request.getParameter("theFunction");
18 }
14 POSTpost请求方式
callback18 30
* 表示允许任何域名跨域访问
6 response.setHeader("Access-Control-Allow-Origin","*");
7 指定特定域名可以访问
8 10 11 List<Student> studentList =13 JSONArray jsonArray =14 String result =15
16 17 String callback = request.getParameter("callback"18 19 result = callback + "(" + result + ")"20
21 22 }