JSON(JavaScript Object Notation)和JSONP(JSON with Padding)虽然只有一个字母的差别,但其实他们根本不是一回事儿:JSON是一种数据交换格式,而JSONP是一种依靠开发人员的聪明才智创造出的一种非官方跨域数据交互协议。JSONP解决了ajax跨域请求的问题,JSONP只是解决跨域请求方案中的一种。
下面基于Servlet简单介绍一下JSONP接口的开发流程:
1, 创建一个Servlet接口JsonpServlet
packagey.u.s.jsonp.servlet; importcom.alibaba.fastjson.JSONObject; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjava.io.IOException; /** *Createdbywangwenjinon2017/3/1. */ publicclassJsonpServletextendsHttpServlet{ @Override protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ Stringcallback=req.getParameter("callback"); resp.setCharacterEncoding("UTF-8"); JSONObjectjo=newJSONObject(); jo.put("Result","remotereturnvalue"); System.out.println(jo.toJSONString()); System.out.println(jo.toString()); resp.getWriter().print(callback+"("+jo.toJSONString()+");"); } @Override protectedvoiddoPost(HttpServletRequestreq,IOException{ doGet(req,resp); } }
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <scripttype="text/javascript"> varlocalHandler=function(data){ alert('iamlocalfun,canbecalledbyremoteserver,remoteserverreturndata:'+data.result); }; varurl="http://localhost/jsonpServlet?callback=localHandler"; varscript=document.createElement('script'); script.setAttribute('src',url); document.getElementsByTagName('head')[0].appendChild(script); </script> </head> <body> </body> </html>原文链接:https://www.f2er.com/json/289004.html