JSONP跨域数据调用

时间:2021-12-19 11:39:03

引自:http://kb.cnblogs.com/page/139725/

Web页面上调用js文件时则不受是否跨域的影响(不仅如此,我们还发现凡是拥有”src”这个属性的标签都拥有跨域的能力,比如<script>、<img>、<iframe>);

JSONP通过将数据(json)格式化为js的形式来实现跨域的数据调用。

<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!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=GB18030">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="jquery-1.9.1.js"></script> <script> function handleData(data){
alert(JSON.stringify(data)); } function loadData(){
var url = "/myweb/TestJsonp?code=CA1998&callback=handleData"; //跨域url
// 提供jsonp服务的url地址(不管是什么类型的地址,最终生成的返回值都是一段javascript代码)
// 创建script标签,设置其属性
var script = document.createElement('script');
script.setAttribute('src', url);
// 把script标签加入head,此时调用开始
document.getElementsByTagName('head')[0].appendChild(script);
} function loadAjax(){
var url = "/myweb/TestJsonp?code=CA1998"; //跨域url
$.ajax({
type: "get", //jsonp 类型下只能使用GET,不能用POST,这里不写默认为GET
async: false,
url: url,
dataType: "jsonp",
jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
// jsonpCallback:"handleData",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
success: function(json){
handleData(json);
alert('您查询到航班信息');
},
error: function(){
alert('fail');
}
});
}
</script>
<body onload="loadAjax()"> </body>
</html>
package bookstore;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class TestJsonp
*/
@WebServlet("/TestJsonp")
public class TestJsonp extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public TestJsonp() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request,response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String code = request.getParameter("code");
String callback = request.getParameter("callback");
response.getWriter().write(
callback+"({code:'"+code+"'})");
} }