使用ajax傳送post請求(切換圖片)
阿新 • • 發佈:2019-02-06
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>切換圖片</title>
<style type="text/css">
body{
text-align: center;
}
#img{
width: 220px;
height: 220px;
border : 1px solid #000;
margin: 0 auto;
}
#text{
width: 220px;
height: 100px;
border: 1px solid #000;
margin: 10px auto;
}
</style>
</head>
<body>
<h1>切換圖片</h1>
<div id="img">
</div >
<div id="text"></div>
<input type="button" class='starBtn' value='海賊王' data-star='onePiece'>
<input type="button" class='starBtn' value='李彥巨集' data-star='lyh'>
<input type="button" class='starBtn' value='馬雲' data-star='my'>
<script type="text/javascript" >
var btns = document.querySelectorAll(".starBtn");
// 繫結事件
for(var i = 0; i <btns.length; i++){
btns[i].onclick = function(){
var ajaxObj = new XMLHttpRequest();
ajaxObj.open("post","04changeimg.php");
ajaxObj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxObj.send('starName='+this.dataset['star']);
ajaxObj.onreadystatechange = function(){
if(ajaxObj.readyState==4&&ajaxObj.status==200){
//
console.log(ajaxObj.responseText);
//擷取字串
var starArr = ajaxObj.responseText.split("|");
//console.log(starArr);
document.querySelector("#img").style.background = 'url('+starArr[0]+') no-repeat center/cover ';
document.querySelector("#text").innerHTML = starArr[1];
}
};
};
}
</script>
</body>
</html>
php程式碼
<?php
header('content-type:text/html;charset=utf-8');
$imginfo = array(
'onePiece' => array('img/onePiece.jpg','我是要做海賊王的男人!' ),
'lyh' => array('img/liyanhong.jpg','我是百度背後的男人!'),
'my' => array('img/mayun.jpg','我是淘寶背後的男人!')
);
$key = $_POST['starName'];
$name = $imginfo[$key];
$pic = $name[0];
$text = $name[1];
echo $pic;
// 進行分割,方便擷取字串
echo "|";
echo $text;
?>