加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

jsonp 跨域问题

发布时间:2020-12-16 19:42:59 所属栏目:百科 来源:网络整理
导读:一.客户端 Html代码 !DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd" html head meta http-equiv = "Content-Type" content = "text/html;charset=UTF-8" title Inserttitlehere / script type = "text/jav

一.客户端

Html代码
  1. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
  2. <htmlheadmetahttp-equiv="Content-Type"content="text/html;charset=UTF-8"title>Inserttitlehere</scripttype="text/javascript"src="resource/js/jquery-1.7.2.js">scriptscripttype="text/javascript" $(function(){
  3. /*
  4. //简写形式,效果相同
  5. $.getJSON("http://app.example.com/base/json.do?sid=1494&busiId=101&jsonpCallback=?",
  6. function(data){
  7. $("#showcontent").text("Result:"+data.result)
  8. });
  9. */
  10. $.ajax({
  11. type:"get",250); line-height:18px"> async:false,250); line-height:18px"> url:"http://app.example.com/base/json.do?sid=1494&busiId=101",250); line-height:18px"> dataType:"jsonp",//数据类型为jsonp
  12. jsonp:"jsonpCallback",//服务端用于接收callback调用的function名的参数
  13. success:function(data){
  14. },250); line-height:18px"> error:function(){
  15. alert('fail');
  16. }
  17. bodydivid="showcontent">Result:div>

二.服务器端

Java代码
    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,0)">1)+")");//返回jsonp格式数据
  24. out.flush();
  25. out.close();
  26. }catch(IOExceptione){
  27. e.printStackTrace();
  28. }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读