实例一、
<script src="http://www.w3school.com.cn/jquery/jquery.js" type="text/javascript"></script>
<script>
$.ajax({
url: "http://www.w3school.com.cn/jquery/test1.txt",
dataType: 'jsonp'
});
//实际请求链接: http://www.w3school.com.cn/jquery/test1.txt?callback=jQuery161004884608048588346_1545379318664&_=1545379542300
$.ajax({
url: "http://www.w3school.com.cn/jquery/test1.txt",
dataType: 'jsonp',
jsonp: 'callbackFun',
jsonpCallback: 'callbackFunName'
});
//实际请求链接: http://www.w3school.com.cn/jquery/test1.txt?callbackFun=callbackFunName&_=1545379747126
</script>
实例二、
<html>
<body>
<script src="http://www.w3school.com.cn/jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function showUser(data) {
alert(data.name + " " + data.age)
}
$(document).ready(function () {
$("#button").click(function () {
$.ajax({
url: "http://localhost:8080/test",
data: {
name: 'xiaohua',
age: '100'
},
dataType: 'jsonp',
jsonpCallback: 'showUser'
});
});
});
</script>
<button id="button" type="button">请求</button>
</body>
</html>
public void test(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/plain");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
String callback = request.getParameter("callback");//
Map map = new HashMap();
map.put("name", request.getParameter("name"));
map.put("age", request.getParameter("age"));
String s = JSONObject.fromObject(map).toString();
PrintWriter out = response.getWriter();
out.println(callback + "(" + s + ")");//返回jsonp格式数据
out.flush();
out.close();
}
实例三、
<html>
<body>
<script src="http://www.w3school.com.cn/jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function showUser(data) {
alert(data.name + " " + data.age)
}
function jsonp(url, callbackFun) {
var JSONP = document.createElement("script");
JSONP.type = "text/javascript";
JSONP.src = url + '&callback=' + callbackFun;
document.getElementsByTagName("head")[0].appendChild(JSONP);
setTimeout(function () {document.getElementsByTagName("head")[0].removeChild(JSONP)}, 1000)
}
$(document).ready(function () {
$("#button").click(function () {
jsonp('http://localhost:8080/test?name=xiaohua&age=1001', 'showUser')
});
});
</script>
<button id="button" type="button">请求</button>
</body>
</html>