JSONP超简单例子,一看就能上手
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{@OverrideprotectedvoiddoGet(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()+");");}@OverrideprotectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{doGet(req,resp);}}
2, 创建一个html文件,并调用JSONP接口
<!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>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。