模拟jsonp原理
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function callback(user) {
alert("hello,"+user.name)
}
</script>
<script type="text/javascript" src="/jsonp?method=callback"></script>
</body>
</html>
servlet
package com.wanggs.web.jq;
/**
* @author Wgs
* @version 1.0
* @create:2018/06/04
*/
@WebServlet("/jsonp")
public class JsonpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
String method = req.getParameter("method");
User user = new User("tom",12);
String json = JSON.toJSONString(user);
Writer out = resp.getWriter();
out.append(method+"("+json+")");
out.flush();
out.close();
}
}
测试
http://localhost/jq/jsonp.jsp
callback({"age":12,"name":"tom"})
JSONP
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="btn">JSONP</button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#btn").click(function () {
$.getJSON("/jsonp?method=?").done(function (data) {
alert(data.name)
}).error(function () {
alert("系统错误!")
});
});
</script>
</body>
</html>
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="btn">JSONP</button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#btn").click(function () {
$.ajax({
url : '/jsonp?method=?',
type : 'GET',
dataType: 'jsonp', // 表示要用 JSONP 进行跨域访问
success : function(data) {
alert(data.name)
}
});
});
</script>
</body>
</html>
image.png
image.png
jsonp调用有道api
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" id="word"> <button id="btn">翻译</button>
<div id="result"></div>
<script src="/static/js/jquery-1.11.3.min.js"></script>
<script>
$(function(){
$("#btn").click(function () {
$("#result").html("");
var word = $("#word").val();
var url = "http://fanyi.youdao.com/openapi.do?keyfrom=kaishengit&key=1587754017&type=data&doctype=jsonp&callback=?&version=1.1&q="+word;
$.getJSON(url).done(function(data){
var array = data.basic.explains;
for(var i =0;i< array.length;i++) {
$("<p></p>").text(array[i]).appendTo($("#result"));
}
}).error(function(){
alert("服务器异常");
});
});
});
</script>
</body>
</html>
fastJson JSONPObject
package com.wanggs.web.jq;
/**
* @author Wgs
* @version 1.0
* @create:2018/06/04
*/
@WebServlet("/jsonp")
public class JsonpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
// 必须是callback: jQuery33101920591678805521_1528275197482
String method = req.getParameter("callback");
User user = new User("tom",12);
JSONPObject jsonp = new JSONPObject(method);
jsonp.addParameter(user);
Writer out = resp.getWriter();
out.append(jsonp.toJSONString());
out.flush();
out.close();
}
}
image.png
script
$.ajax({
url : '/jsonp',
type : 'GET',
dataType: 'jsonp', // 表示要用 JSONP 进行跨域访问
success : function(data) {
alert(data.name+"--->>"+data.age)
}
});
SpringMvc
服务器端:
- 使用 produces 设置响应的 Content-Type
- 返回 JSONP 格式的字符串,例如jQuery21107523536464367151_1492668511201("Goo")
import com.alibaba.fastjson.JSONPObject;
@GetMapping(value="/jsonp-test", produces="application/javascript;charset=UTF-8")
@ResponseBody
public String jsonpTest(@RequestParam String callback) {
JSONPObject jsonp = new JSONPObject(callback);
jsonp.addParameter("Goo"); // 或则 Object
return jsonp.toString();
}
浏览器端
$.ajax({
url : 'http://127.0.0.1:8080/jsonp-test',
type : 'GET',
dataType: 'jsonp', // 表示要用 JSONP 进行跨域访问
success : function(data) {
console.log(data);
}
});
网友评论