Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:好直观
1.HTMLindex.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jsonp请求</title>
</head>
<style>
table {
border: 1px solid;
text-align: center;
margin-top: 20px;
}
td {
border: 1px solid;
}
thead {
text-align: left;
padding: 0 10px;
}
div {
margin: 10px 500px;
}
</style>
<body>
<div>
<button>获取数据</button>
<table></table>
</div>
</body>
<script>
function handle(data) {
var table = document.querySelector("table");
var obj = JSON.parse(data);
console.log(obj);
var ta = "<thead>" + obj.title + "</thead>";
ta += "<tr><td>编号</td><td>名称</td> <td>价格</td><td>总价</td></tr>";
ta +=
"<tr><td>" +
obj.info.id +
"</td><td>" +
obj.info.name +
"</td><td>" +
obj.info.price +
obj.info.unit +
"</td><td>" +
obj.info.price * obj.info.num +
"</td></tr>";
table.innerHTML = ta;
}
var btn = document.querySelector("button");
btn.addEventListener("click", function () {
//新建script标签
var script = document.createElement("script");
//注:回调函数名(例:&jsp=handle)一定要写在URL最后
script.src = "http://jsonp.cn/Jsonp.php?id=3&jsp=handle";
document.head.appendChild(script);
});
</script>
</html>
2.后端Jsonp.php
:已设置在http://jsonp.cn
域名下
<?php
//设置编码格式请求头
header('Content-Type:text/html;charset=utf-8 ');
//获取参数
$id = $_GET['id'];
//前端回调函数名称
$callback = $_GET['jsp'];
//模拟获取到数据库的数据
$goods =[
'{"id":GD1002,"name":苹果,"price":8,"unit":元/斤,"num":6}',
'{"id":GD1042,"name":哈密瓜,"price":10.5,"unit":个,"num":4',
'{"id":"GD1026","name":"西瓜","price":6.5,"unit":"个","num":10}',
'{"id":GD1034,"name":樱桃,"price":125,"unit":箱,"num":7}'
];
//判断$id是否在数组的所有当中
if(array_key_exists($id-1,$goods)){
$good = $goods[$id-1];
}
$json='{"title":"商品信息表","info":'.$good.'}';
echo $callback."(".json_encode($json).")";
<!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>
<div>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
</div>
</body>
<script>
//绑定父级点击事件
document.querySelector("div").addEventListener("click", function (eve) {
addclick(eve);
});
function addclick(eve) {
//target:触发事件元素
//currentTarget:绑定事件元素
//tagName:获取元素名称
alert(
"当前点击的是:" +
eve.target.innerText +
";绑定点击元素是:" +
eve.currentTarget.tagName
);
}
</script>
</html>