首页 > Web开发 > 详细

跨域访问方法介绍(6)--使用 JSONP

时间:2021-06-27 17:00:35      阅读:23      评论:0      收藏:0      [点我收藏+]

JSONP(JSON with Padding) 是 JSON 的一种"使用模式",可以让网页从别的域名(网站)那获取资源,即跨域读取数据。JSONP 的优势在于支持老式浏览器,兼容性好(兼容低版本IE),缺点是只支持 GET 请求,不支持 POST 请求。本文主要介绍 JSONP 的使用方法,文中所使用到的软件版本:Chrome 90.0.4430.212、jquery 1.12.4、Spring Boot 2.4.4、jdk1.8.0_181。

1、实现思路

网页通过添加一个 <script> 元素,向服务器请求 JSON 数据,服务器收到请求后,将数据放在一个指定名字的回调函数的参数位置传回来。

2、服务端实现(Spring 版)

假设访问 : http://localhost:8080/test/getStudents?callback=showStudents
假设期望返回数据:[{"name":"李白","age":"20"},{"name":"杜甫","age":"21"}]
真正返回到客户端的数据为: showStudents([{"name":"李白","age":"20"},{"name":"杜甫","age":"21"}])

package com.abc.demo.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/test")
@Controller
public class TestController {
    @RequestMapping("/getStudents")
    public void getStudents(String callback, HttpServletResponse response) throws IOException {
        //返回前台的结果数据
        List<Map<String, String>> result = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("name", "李白");
        map.put("age", "20");
        result.add(map);
        map = new HashMap<>();
        map.put("name", "杜甫");
        map.put("age", "21");
        result.add(map);
        response.setCharacterEncoding("utf-8");
        String javascript = callback + "(" + new ObjectMapper().writeValueAsString(result) + ")";
        response.getWriter().println(javascript);
    }
}

3、前台实现

3.1、原生写法(testJsonp.html)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSONP 测试</title>

</head>
<body>
    <div id="students"></div>
</body>
<script type="text/javascript" src="./jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    
</script>
<script type="text/javascript">
    function showStudents(result) {
        let html = <ul>;
        for(let i = 0; i < result.length; i++) {
            html += <li>姓名: + result[i].name + ,年龄: + result[i].age +  </li>;
        }
        html += </ul>;
        document.getElementById(students).innerHTML = html;
    }
</script>
<script type="text/javascript" src="http://localhost:8080/test/getStudents?callback=showStudents"></script>
</html>

3.2、Jquery 写法(testJsonpJquery.html)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSONP 测试(Jquery)</title>

</head>
<body>
    <div id="students"></div>
</body>
<script type="text/javascript" src="./jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $.getJSON("http://localhost:8080/test/getStudents?callback=?", function(result) {
        let html = <ul>;
        for(let i = 0; i < result.length; i++) {
            html += <li>姓名: + result[i].name + ,年龄: + result[i].age +  </li>;
        }
        html += </ul>;
        document.getElementById(students).innerHTML = html;
    });
</script>
</html>

3、测试

用浏览器直接打开 html 文件即可

 技术分享图片技术分享图片

跨域访问方法介绍(6)--使用 JSONP

原文:https://www.cnblogs.com/wuyongyin/p/14835918.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!