<!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>Test</title> <script type="text/javascript"> function myChange (arg) { var str = arg.value.toString(); console.debug(str) document.cookie = "var=" + str; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ document.getElementById("text1").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "getText.php", true); xmlhttp.send(); } </script> </head> <body> <div> <select id="select1" onchange="myChange(this)"> <option>台北市</option> <option>新北市</option> </select> </div> <div id="text1"></div> </body> </html>
<?php $str = $_COOKIE["var"]; if($str != ""){ echo "<label>$str</label>"; }else{ echo "No data"; } ?>
成果如下:
參考資料:
http://stackoverflow.com/questions/16007435/assign-javascript-value-to-php-variable
http://www.w3schools.com/js/js_cookies.asp
http://www.w3schools.com/php/php_cookies.asp
http://www.w3schools.com/php/php_ajax_php.asp
http://tw2.php.net/setcookie