JSONP通过ID货物商品信息
- 准备环境:两个端口不一样,构成跨域请求的条件。
- 获取数据的网址:http://www.a.com 本机地址:http://www.php.com
- goods.html 通过点击事件查看商品信息(本地文件)
- goods.php 处理商品信息,返回
演示代码:goods.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>点击按钮获取商品信息</title>
</head>
<body>
<button>查看</button>
<script>
function handle(data)
{
console.log(data);
var ul = document.createElement("ul");
var obj = JSON.parse(data);
ul.innerHTML += '<li>' + obj.title + '</li>';
ul.innerHTML += '<li>' + obj.goods.type + '</li>';
ul.innerHTML += '<li>' + obj.goods.goodname + '</li>';
ul.innerHTML += '<li>' + obj.goods.price + '</li>';
document.body.appendChild(ul);
}
var but =document.querySelector("button");
but.addEventListener("click",function()
{
var script = document.createElement("script");
script.src = "http://www.a.com/goods.php?id=2&jsonp=handle";
document.head.appendChild(script);
});
</script>
</body>
</html>
演示代码:goods.php
<?php
header("Content-type:text/html;charset=utf-8");
//设置默认字符集
$id = $_GET['id'];
$callback = $_GET['jsonp'];
$goodss = [
'{"type":"大家电","goodsname":"电视机","price":"3200"}',
'{"type":"通讯设备","goodsname":"小米10 pro","price":"6800"}',
'{"type":"通讯设备","goodsname":"苹果12 pro","price":"13200"}',
'{"type":"办公设备","goodsname":"联想Thinkpad","price":"6200"}',
'{"type":"家居","goodsname":"罗莱家纺","price":"530"}'
];
//由于传入ID的值从1开始,通过$id-1才能得到查询的正确id
if(array_key_exists(($id-1),$goodss))
{
//查询$goods中键值等于$id的商品。
$goods = $goodss[$id-1];
}
// $json = '{}'; 定义josn格式
$json = '{
"title":"商品信息",
"goods": '. $goods .'
}';
//返回handle函数
$jsons = json_encode($json);
echo $callback.'('. $jsons .')';
示例图:
事件代理的案例
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件代理</title>
</head>
<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
<li>5555</li>
</ul>
<body>
<script>
var ul = document.querySelector("ul");
ul.addEventListener("click",function(ev)
{
var lis = ev.target;
if(lis.tagName.toLowerCase()=='li')
{
lis.style.background="red";
}
});
ul.addEventListener("mouseout",function(ev)
{
ev.target.style.background = "";
});
</script>
</body>
</html>
示例图: