標籤:asc http XML 修改 head lang 資料 var 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]; ?>
ajax切換明星頭像!