SpringMVC Jsonp跨域

本文详细介绍了一个关于JSONP跨域请求的实战案例,包括两个服务的搭建:一个提供JSONP响应的服务和一个发起跨域请求的前端服务。通过具体的代码示例,展示了如何在前端使用jQuery发起JSONP请求,并在后端正确处理并返回JSONP格式的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务一

http://localhost:8080/index

端口配置

server.port=8080
spring.mvc.view.suffix=.html

controller

@Controller
public class JsonpController {
    @GetMapping("index")
    public String index() {
        System.out.println("进入首页!");
        return "index";
    }
}

html跨域请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        function println(data) {
            console.log(data);
            if (data.result == 0) {
                console.log("success");
            }
            if (data.result == 1) {
                console.log("fail");
            }
        }
        function jsonp_test() {
            $.ajax({
                type: "get",
                url: "http://localhost:8086/test/jsonp",
                dataType: "jsonp",
                jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
                jsonpCallback: "println", //返回后调用的处理函数
                error: function () { //请求出错的处理
                    alert("请求出错");
                }
            });
        }
    </script>
</head>
<body onload="jsonp_test()">
</body>
</html>

服务二

http://localhost:8086/test/jsonp

controller

@RestController
@RequestMapping("test")
public class TestController {
    @RequestMapping("jsonp")
    public String jsonp(@RequestParam("callback") String callback) {
        System.out.println("jsonp");
        return callback + "({'result':0})";
    }

}

测试访问地址

http://localhost:8080/index

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值