jsonp协议 java服务端、JQuery客户端 简单实现原理

原文链接:https://blog.csdn.net/Activity_Time/article/details/96440806

1. 概述

Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。

为什么我们从不同的域(网站)访问数据需要一个特殊的技术( JSONP )呢?这是因为同源策略。

同源策略,它是由 Netscape 提出的一个著名的安全策略,现在所有支持 JavaScript 的浏览器都会使用这个策略。

ajax本身是不可以跨域的,
通过产生一个script标签来实现跨域。因为script标签的src属性是没有跨域的限制的。

其实设置了dataType: 'jsonp'后,$.ajax方法就和ajax XmlHttpRequest没什么关系了,取而代之的则是JSONP协议。JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问。

2. 客户端实现原理
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSONP 实例</title>
</head>
<body>
<div id="divCustomers"></div>
<script type="text/javascript">
// 回调函数
function callbackFunction(result)
{
    document.getElementById('divCustomers').innerHTML = result;
}
</script>
<!-- 访问菜鸟教程的jsonp示例 -->
<script type="text/javascript" src="https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>
3. JQuery实现
$.getJSON("https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?",function(json){ 
alert(json);
//要求远程请求页面的数据格式为: ?(json_data) 
//例如: 
//?("test") alert(json[0]._name); 
//JQuery会随机生成一个函数名 例如:jQuery110206760198562063544_1563445396212
}); 

也可以使用ajax函数

		$.ajax('https://www.runoob.com/try/ajax/jsonp.php', {
                method: 'post',
                contentType: 'application/javascript;charset=utf-8',
             
                dataType: 'jsonp',		// jsonp方式
                jsonp: 'jsoncallback',	// 回调函数名-参数名
                success: function (result) {
                    //  回调函数
                    console.log(result);
                }
            });
            $("#jkl").html(parseInt($("#jkl").html()) + 1);
        }

生成url : https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=jQuery11020184377763744622_1563446095229&_=1563446095230

4. 服务端原理
protected void service(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
		
		String msg = "测试信息";
		
		// jsonp跨域协议
		resp.addHeader("content-type", "application/javascript");
		String func = request.getParameter("jsoncallback");
		PrintWriter pw = resp.getWriter();
		pw.print(func + "('" + msg + "');");
		pw.flush();
	}

参考文章:

菜鸟教程:https://www.runoob.com/jquery/jquery-tutorial.html
jsonp原理详解:https://blog.csdn.net/hansexploration/article/details/80314948
jquery中ajax处理跨域的三大方式:https://www.jb51.net/article/77470.htm

原文地址:https://www.cnblogs.com/ACTIM/p/11230083.html