ajax切换明星头像!

html部分:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .showBox{
            width: 200px;
            height: 200px;
            margin: 100px auto;
            border: 1px solid gray;
        }
    </style>
</head>
<body>
    <div class="showBox"></div>
    <input type="button" value='彭于晏' data-name = 'pyy'>
    <input type="button" value='周董' data-name = 'jay'>
    <input type="button" value='陈老师^_^' data-name = 'cgx'>
</body>
</html>
<script type="text/javascript">
    var btns =  document.querySelectorAll('input');
     //  循环绑定点击事件
     for (var i = 0; i < btns.length; i++) {
         btns[i].onclick = function(){
             // 创建
             var ajax = new XMLHttpRequest();

             // 修改 url的值 01.changeImg.php?starName =

             // 获取 data-自定义属性
             console.log(this.dataset.name);

             // 设置
             ajax.open('get','01.changeImg.php?starName='+this.dataset.name);

             // 发送
             ajax.send();

             // 注册
             ajax.onreadystatechange = function(){
                 if(ajax.readyState==4 &&ajax.status==200){
                     // 判断并使用
                     console.log(ajax.responseText);

                     // 设置 展示div的 background属性
                     document.querySelector('.showBox').style.background = 'url('+ajax.responseText+') no-repeat center/cover';
                 }
             }

             
         }
     };
</script>

PHP部分:

<?php 
    // 获取提交的数据 明星数据 key
    $starKey =  $_GET['starName'];

    // 关系型数组 key->value
    $starArr = array(
            'pyy'=>'img/pyy.jpg',
            'jay'=>'img/jay.jpg',
            'cgx'=>'img/cgx.jpg'
        );

    // echo value
    // 通过key  获取对应的 value
    echo $starArr[$starKey];
    
 ?>
原文地址:https://www.cnblogs.com/famensaodiseng/p/6265511.html