ajax+callback解决java访问接口跨域问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/han_xiaoxue/article/details/79297795

在开发当中,调接口的时候发生如下报错。
No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8080’ is therefore not allowed access.

这种其实是跨域问题。
解决办法:
java代码:

@RequestMapping(value = "/video/{urlName}")
    public String playVideo(HttpServletRequest req, @PathVariable String urlName){
        Map<String,Object> map = new HashMap<String,Object>();
        String theName = "处理。。。";
        map.put("theName ",theName );
        String callback = req.getParameter("callback");
//        Gson go =new Gson();
        Gson go =new GsonBuilder().disableHtmlEscaping().create();
        String json = go.toJson(map);
        return callback+"("+json+")";
    }

js代码

 $(function(){
        $.ajax({
            url: 'http://192.166.11.9:8389/video/e66801-435-4fdf-9589-395c450085f9',
            type: 'post',
            dataType:'jsonp',
            jsonp: "callback",
            success:function(data){
                console.log(data.theName );
            },
            error:function(data){
                console.log(data)
            }
        });
    })

控制台输出想要内容,成功
这里写图片描述

猜你喜欢

转载自blog.csdn.net/han_xiaoxue/article/details/79297795