zoukankan      html  css  js  c++  java
  • springmvc jsonp 跨域调用的例子

    html代码 :

    <!DOCTYPE html>
    <html>
    <head>
        <title>json跨域调用的例子</title>
    </head>
    <body>
    <script type="text/javascript" src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function(){
            $.ajax({
                type : "get",
                async: false,
                url: "http://127.0.0.1:8080/seg/getSeg?chineseSentence=%E6%88%91%E7%88%B1%E5%8C%97%E4%BA%AC"+'&callback=?',//请求的地址
                dataType: "jsonp",
                jsonp:"callback", //这个参数会出现在springmvc的方法中
                success : function(data) {
                    
                    alert(data.Age+' '+data.UserName);
                    
                }

            });
        });
    </script>
    </body>
    </html>

    springmvc控制器java代码:

    package com.example.segment.controller;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    @RequestMapping(value = "/seg/*")
    public class ChineseWordsSegmentation {

        private static final Logger LOG = LoggerFactory.getLogger(ChineseWordsSegmentation.class);
        private ChineseWordsSegment seg;

        @RequestMapping(value = "getSeg", method = RequestMethod.GET, produces = {"application/json; charset=UTF-8"})
        @ResponseBody
        public String getSeg(@RequestParam String chineseSentence, String callback){
            String jsonp = "";
            String result = "{"UserName":"abc","Age":"25"}";

            LOG.info(seg.getSegmentation(chineseSentence).toString());


            if(callback.length() > 0){

                jsonp = callback + "(" + result + ")";

            }
            return jsonp;


        }

     

    }

  • 相关阅读:
    shell基础--变量的数值计算
    shell基础--字符串和变量的操作
    shell基础--shell特殊变量
    Asp.net MVC 控制器扩展方法实现jsonp
    ASP.NET web api 跨域请求
    asp.net Web API简单的特性路由配置
    ASP.Net Web API 输出缓存 转载 -- Output caching in ASP.NET Web API
    基础拾遗 C# Json 与对象相互转换
    内存溢出和内存泄漏
    软件测试面试题(一)
  • 原文地址:https://www.cnblogs.com/herosoft/p/8288938.html
Copyright © 2011-2022 走看看