JSON(JavaScript Object Notation)和JSONP(JSON with Padding)虽然只有一个字母的差别,但其实他们根本不是一回事儿:JSON是一种数据交换格式,而JSONP是一种依靠开发人员的聪明才智创造出的一种非官方跨域数据交互协议。JSONP解决了ajax跨域请求的问题,JSONP只是解决跨域请求方案中的一种。
下面基于Servlet简单介绍一下JSONP接口的开发流程:
1, 创建一个Servlet接口JsonpServlet
package y.u.s.jsonp.servlet; import com.alibaba.fastjson.JSONObject; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by wangwenjin on 2017/3/1. */ public class JsonpServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String callback = req.getParameter("callback"); resp.setCharacterEncoding("UTF-8"); JSONObject jo = new JSONObject(); jo.put("Result","remote return value"); System.out.println(jo.toJSONString()); System.out.println(jo.toString()); resp.getWriter().print(callback + "(" + jo.toJSONString() + ");"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
2, 创建一个html文件,并调用JSONP接口
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> var localHandler = function(data){ alert('i am local fun,can be called by remote server,remote server return data :' + data.result); }; var url = "http://localhost/jsonpServlet?callback=localHandler"; var script = document.createElement('script'); script.setAttribute('src', url); document.getElementsByTagName('head')[0].appendChild(script); </script> </head> <body> </body> </html>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。