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 檔案即可


轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/288581.html
標籤:其他
上一篇:分享Sql性能優化的一些建議
下一篇:分享Sql性能優化的一些建議
