·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> JQuery+ajax+jsonp 跨域访问

JQuery+ajax+jsonp 跨域访问

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

JQuery+Ajax+jsonp 跨域访问

Jsonp(JSON with Padding)是资料格式 json 的一种“使用模式”,可以让网页从别的网域获取资料。

关于Jsonp更详细的资料请参考http://baike.baidu.com/view/2131174.htm,下面给出例子:

一.客户端

Html代码收藏代码
  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",
  19. async:false,
  20. url:"http://app.example.com/base/json.do?sid=1494&busiId=101",
  21. dataType:"jsonp",//数据类型为jsonp
  22. jsonp:"jsonpCallback",//服务端用于接收callback调用的function名的参数
  23. success:function(data){
  24. $("#showcontent").text("Result:"+data.result)
  25. },
  26. error:function(){
  27. alert('fail');
  28. }
  29. });
  30. });
  31. </script>
  32. <body>
  33. <divid="showcontent">Result:</div>
  34. </body>
  35. </html>

二.服务器端

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