<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>跨域请求:PHP函数回调(带参)</title>
</head>
<body>
<script>
//data:跨域数据
//1.函数声明:当前脚本
function hello(data){
// console.log(data.name)
const str =`
<ul>
<li>序号:${data.id}</li>
<li>姓名:${data.name}</li>
<li>邮箱:${data.email}</li>
</ul>
`
document.body.insertAdjacentHTML('afterbegin',str)
}
</script>
<!-- 2. 调用函数语句,在跨域脚本中-->
<!-- <script src="http://jsonp.io/demo.js"></script> -->
<script>
function getJSON(url){
const script = document.createElement('script');
script.src = url;
document.body.append(script);
}
getJSON('http://jsonp.io/demo1.php?callback=hello&id=1');
</script>
</body>
</html>
PHP示范:
<?php
$users = [
['id' => 1, 'name' => '老六', 'email' => 'nx99@qq.com'],
['id' => 2, 'name' => '老七', 'email' => 'nx88@qq.com'],
['id' => 3, 'name' => '老八', 'email' => 'nx77@qq.com'],
];
$id = $_GET['id'];
$callback = $_GET['callback'];
$user = array_filter($users, function ($item) use ($id) {
return $item['id'] == $id;
});
$data = json_encode(array_pop($user));
//通知返回字符串的形式,将回调函数写回去,在原页面调用数据,规避了跨域调用数据
echo "$callback($data)";
HTML代码示范:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>跨域请求:PHP跨域回调(带参)</title>
</head>
<body>
<script>
//data:跨域数据
//1.函数声明:当前脚本
function say(data) {
// console.log(data.name)
const str = `
<ul>
<li>序号:${data.id}</li>
<li>姓名:${data.name}</li>
<li>邮箱:${data.email}</li>
</ul>
`;
document.body.insertAdjacentHTML('afterbegin', str);
}
</script>
<!-- 2. 调用函数语句,在跨域脚本中-->
<!-- <script src="http://jsonp.io/demo.js"></script> -->
<script>
function getJSON(url) {
//ajax
fetch(url)
.then(res => res.json())
.then(json => say(json));
}
getJSON('http://jsonp.io/demo2.php?callback=say&id=1');
</script>
</body>
</html>
PHP代码示范
<?php
header("Access-Control-Allow-Origin: *");
$users = [
['id' => 1, 'name' => '老六', 'email' => 'nx99@qq.com'],
['id' => 2, 'name' => '老七', 'email' => 'nx88@qq.com'],
['id' => 3, 'name' => '老八', 'email' => 'nx77@qq.com'],
];
$id = $_GET['id'];
$callback = $_GET['callback'];
$user = array_filter($users, function ($item) use ($id) {
return $item['id'] == $id;
});
// $data = json_encode(array_pop($user));
echo json_encode(array_pop($user));
// echo "callback($data)";