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;


    }

 

}

posted @ 2018-01-15 17:14  深渊中的鱼  阅读(331)  评论(0编辑  收藏  举报