jsonp原理
借助script标签发送跨域请求,只支持get方法
客户端:client.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JSONP 客户端</title> </head> <body> <script> function jsonp (url, params, callback) { var funcName = 'jsonp_' + Date.now() + Math.random().toString().substr(2, 5) if (typeof params === 'object') { var tempArr = [] for (var key in params) { var value = params[key] tempArr.push(key + '=' + value) } params = tempArr.join('&') } var script = document.createElement('script') script.src = url + '?' + params + '&callback=' + funcName document.body.appendChild(script) window[funcName] = function (data) { callback(data) delete window[funcName] document.body.removeChild(script) } } jsonp('http://localhost/jsonp/server.php', { id: 1 }, function (res) { console.log(res) }) jsonp('http://localhost/jsonp/server.php', { id: 1 }, function (res) { console.log(res) }) </script> </body> </html>
服务器:server.php
<?php $data = array( 'id' => 1, 'name' => 'zs' ); if (empty($_GET['callback'])) { header('Content-Type: application/json'); echo json_encode($data); exit(); } // 如果客户端采用的是 script 标记对我发送的请求 // 一定要返回一段 JavaScript header('Content-Type: application/javascript'); $result = json_encode($data); $callback_name = $_GET['callback']; echo "typeof {$callback_name} === 'function' && {$callback_name}({$result})";