4

java~jsonp的使用

 2 years ago
source link: https://www.cnblogs.com/lori/p/15062547.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

对于一个后端程序来发,它可能会被多个应用调用,而跨域的问题就来了,使用jsonp来解决这个问题是个不错的方式,下面说一下关于jsonp的知识

  • JSONP不是新技术,只是在页面上响应一段js
  • 对于响应的 MIME type ('text/plain')需要注解,它由于受到了X-Content-Type-Options:nosniff的限制,在跨域时你的js是不支持的
  • 基于上面的原因,我们的服务器的接口方法,返回MIME应该是application/javascript

服务端代码

   @GetMapping(value = "/get-user", produces = {"application/javascript"})
    public String users(@RequestParam String name, @RequestParam String callback) {
        String jsonStr = "{'name':'" + name + "'}";
        return callback + "(" + jsonStr + ")";
    }
<script type="text/javascript">
    $.ajax({
        type: "get",
        url: "http://192.168.3.181:9090/get-user?name=lind",
        dataType: 'jsonp',
        jsonp: "callback",
        success: function (response, status, xhr) {
            console.log(response);	//服务器返回的信息
            console.log(xhr.status);	//服务器返回的信息
        },
        error: function () {
            console.log("请求失败");
        }
    });

</script>

跨域请求的结果

服务端实际的响应是个js方法


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK