html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 300px;
height: 300px;
border: 1px solid #000;
margin: 50px auto;
text-align: center;
background-color: skyblue;
}
img {
width: 200px;
height: 200px;
display: block;
margin: 10px auto 10px;
border: 1px solid #000;
}
p {
text-align: center;
background: pink;
}
</style>
<!---->
<script src="ajax封装.js"></script>
<script src="../jquery-3.4.1.js"></script>
<script>
$(function(ev) {
$("button").click(function(ev1) {
ajax({
type: "post",
url: "ajax练习.php",
data: {
"name": $(this).attr("name")
},
timeout: 3000,
success: function(xhr) {
var res = xhr.responseText.split("|")
console.log(res)
$('#title').html(res[0])
$("img").attr("src", res[1])
$("#deg").text(res[2])
},
error: function(xhr) {
alert(xhr.status)
}
})
})
})
</script>
</head>
<body>
</body>
<div>
<p id="title"> 商品标题名称</p>
<img src="" alt="">
<p id="deg">商品描述信息</p>
<button name="nz">女装</button>
<button name="bb">包包</button>
<button name="tx">拖鞋</button>
</div>
</html>
php部分
<?php
//定义字典保存商品信息
$products = array("nz"=>array("title"=>"最美女装","deg"=>"人见人爱,花见花开,甜美系列",
"image"=>"images/nz.jpg"),
"bb"=>array("title"=>"奢华包包","deg"=>"送女友,送情人,送学妹",
"image"=>"images/bb.jpg"),
"tx"=>array("title"=>"最美女鞋","deg"=>"人见人爱,花见花开,甜美系列",
"image"=>"images/tx.jpg"));
//2获取前端传递的参数
$name = $_POST['name'];
//3根据前端传入的key获取对应的字典
$product = $products[$name];
//将小字典的内容取出来返回给前端
echo $product['title'];
echo '|';
echo $product["image"];
echo '|';
echo $product['deg'];
?>
封装的ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!--<script src="../jquery-3.4.1.js"></script>-->
<script src="ajax封装.js"></script>
<script>
window.onload = function(ev) {
var oBtn = document.querySelector("button");
oBtn.onclick = function(ev1) {
/* ajax("POST",
"ajax封装.php", {
"userName": "李开放",
"userPwd": "123456"
//服务器需要的格式:url?key=value&key = value;
}, 3000,
function(xhr) {
alert(xhr.responseText);
},
function(xhr) {
alert("请求失败");
})
};*/
ajax({
success: function(xhr) {
alert(xhr.responseText)
},
url: 'ajax封装.php',
data: {
"userName": "李开放",
"userPwd": "123456"
},
type: "post",
timeout: "3000",
error: function(xhr) {
alert(xhr.status)
}
})
}
}
/* $(function() {
$("button").click(function() {
$.ajax({
type: "GET",
url: "ajax封装.php",
data: "userName=李开放&userPwd=123456 ",
success: function(msg) {
alert(msg);
},
error: function(xhr) {
alert(xhr.status)
}
});
})
})*/
</script>
</head>
<body>
<button>发送请求</button>
</body>
</html>
网友评论