<script> 標籤不受同源策略限制,動態創建指向跨域接口的 script,服務端返回可執行的 JS 代碼(調用預約回調函數),實現跨域數據獲取 — 即 JSONP 模式。
<script>
function request(id, url) {
var old = document.getElementById(id);
if (old) old.parentNode.removeChild(old);
var script = document.createElement('script');
script.id = id;
script.type = 'text/javascript';
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
return script;
}
function userLogin() {
var username = document.getElementById('name').value;
var password = document.getElementById('password').value;
var url = 'https://127.0.0.1:8080/EasyCMS/login.jsp' +
'?name=' + encodeURIComponent(username) +
'&password=' + encodeURIComponent(password) +
'&s=' + Date.now(); // 防緩存
request('loginScript', url);
}
// 約定好的全局回調函數
function myloginState(state) {
if (state === '0') alert('登陸成功');
else alert('登陸失敗');
}
</script>
<body>
用戶名:<input id="name" type="text" />
密碼:<input id="password" type="password" />
<input type="button" value="login" onclick="userLogin()" />
</body>
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String name = request.getParameter("name");
String password = request.getParameter("password");
if ("admin".equals(name) && "admin".equals(password)) {
session.setAttribute("admin", "admin");
%>
myloginState("0");
<% } else { %>
myloginState("1");
<% } %>
myloginState 雙方約定,或由前端傳參 callback=xxxencodeURIComponent 編碼fetch('https://api.example.com/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({name, password})
}).then(r => r.json()).then(data => { /* ... */ });
CORS 是現代跨域標準方案,JSONP 僅作歷史兼容參考。