JSONP技术可以解决AJAX跨域请求的问题。
主要是使用script标签,请求一段JS脚本执行。
-
<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">
-
<html>
-
<head>
-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-
<script type="text/javascript">
-
function callback(data)
-
{
-
alert(data);
-
}
-
</script>
-
</head>
-
<body>
-
<script type="text/javascript" src="./InitServlet"></script>
-
</body>
-
</html>
-
@WebServlet("/InitServlet")
-
public class InitServlet extends HttpServlet {
-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
doPost(request, response);
-
}
-
-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
response.setCharacterEncoding("utf-8");
-
response.getWriter().print("callback('你好')");
-
}
-
-
}
请求返回的结果会直接以JS脚本运行。
需要注意的是,JSONP只以Get方式请求,请求的结果也可能被浏览器缓存。
JQuery可以简化这个流程。
-
<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">
-
<html>
-
<head>
-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-
<script type="text/javascript"
-
src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
-
<script type="text/javascript">
-
$(document).ready(function() {
-
$.getJSON("./InitServlet?jsoncallback=?", function(data) {
-
alert(data);
-
})
-
})
-
</script>
-
</head>
-
<body>
-
</body>
-
</html>
-
@WebServlet("/InitServlet")
-
public class InitServlet extends HttpServlet {
-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
doPost(request, response);
-
}
-
-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
response.setCharacterEncoding("utf-8");
-
String callback = request.getParameter("jsoncallback");
-
response.getWriter().print(callback + "('你好')");
-
}
-
-
}
jsoncallback会自动生成一个随机名称,这个名称就是回调函数的名称。
因为是随机生成的,所以避免了浏览器缓存数据。
从服务器返回的结果
jQuery203022411514748819172_1386078136124('你好')
参考:
http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1062082/
,如需转载,请注明出处,否则将追究法律责任。