如下所示为jsonp跨域请求封装的的ajax代码:
详细解释参看:https://blog.csdn.net/guanmao4322/article/details/88782995
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
url: "http://localhost:9090/student",//访问路径
type: "GET",
dataType: "jsonp", //指定服务器返回的数据类型
jsonp: "callback", //指定参数名称
jsonpCallback: "showData", //指定回调函数名称
});
}
});
//回调函数
function showData (data) {
console.info("调用showData");
var result = JSON.stringify(data);
$("#text").val(result);
}
服务器端:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// * 表示允许任何域名跨域访问
response.setHeader("Access-Control-Allow-Origin", "*");
// 指定特定域名可以访问
//response.setHeader("Access-Control-Allow-Origin", "http:localhost:8080/");
//数据
List<Student> studentList = getStudentList();
JSONArray jsonArray = JSONArray.fromObject(studentList);
String result = jsonArray.toString();
//前端传过来的回调函数名称
String callback = request.getParameter("callback");
//用回调函数名称包裹返回数据,这样,返回数据就作为回调函数的参数传回去了
result = callback + "(" + result + ")";
response.getWriter().write(result);
}
注:在HTML页面中注意引入jQuery.js