JSONP 跨域

前端之家收集整理的这篇文章主要介绍了JSONP 跨域前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
  5. <title>Inserttitlehere</title>
  6. <scripttype="text/javascript"src="resource/js/jquery-1.7.2.js"></script>
  7. </head>
  8. <scripttype="text/javascript">
  9. $(function(){
  10. /*
  11. //简写形式,效果相同
  12. $.getJSON("http://app.example.com/base/json.do?sid=1494&busiId=101&jsonpCallback=?",
  13. function(data){
  14. $("#showcontent").text("Result:"+data.result)
  15. });
  16. */
  17. $.ajax({
  18. type:"get",0); background-color:inherit">async:false,0); background-color:inherit">url:"http://app.example.com/base/json.do?sid=1494&busiId=101",0); background-color:inherit">dataType:"jsonp",//数据类型为jsonp
  19. jsonp:"jsonpCallback",//服务端用于接收callback调用的function名的参数
  20. success:function(data){
  21. },0); background-color:inherit">error:function(){
  22. alert('fail');
  23. }
  24. </script>
  25. <body>
  26. <divid="showcontent">Result:</div>
  27. </body>
  28. </html>

二.服务器端

    importjava.io.IOException;
  1. importjava.io.PrintWriter;
  2. importjava.util.HashMap;
  3. importjava.util.Map;
  4. importjavax.servlet.http.HttpServletRequest;
  5. importjavax.servlet.http.HttpServletResponse;
  6. importnet.sf.json.JSONObject;
  7. importorg.springframework.stereotype.Controller;
  8. importorg.springframework.web.bind.annotation.RequestMapping;
  9. @Controller
  10. publicclassExchangeJsonController{
  11. @RequestMapping("/base/json.do")
  12. voidexchangeJson(HttpServletRequestrequest,HttpServletResponseresponse){
  13. try{
  14. response.setContentType("text/plain");
  15. response.setHeader("Pragma","No-cache");
  16. response.setHeader("Cache-Control","no-cache");
  17. response.setDateHeader("Expires",0);
  18. Map<String,String>map=newHashMap<String,String>();
  19. map.put("result","content");
  20. PrintWriterout=response.getWriter();
  21. JSONObjectresultJSON=JSONObject.fromObject(map);//根据需要拼装json
  22. StringjsonpCallback=request.getParameter("jsonpCallback");//客户端请求参数
  23. out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据
  24. out.flush();
  25. out.close();
  26. }catch(IOExceptione){
  27. e.printStackTrace();
  28. }

猜你在找的Json相关文章