如何将颜色选择器的值保存到mysql中

时间:2013-11-26 04:54:51

标签: php mysql html5

如何将颜色选择器的值保存到mysql中,我有更改背景的代码,但我想使用php脚本将颜色选择器的值保存到我的sql中。请帮助我... 谢谢^^

<!DOCTYPE HTML>
<html>
   <head>
      <title>Control Color</title>
      <script type="text/javascript">
         window.onload = init;
         function init () {
            var formulir = document.getElementById("formulir");
            formulir.onsubmit = function() {
               var color1 = document.getElementById("color1").value;
               document.bgColor = color1;
               return false; // Batalkan submit
            }      
         }
      </script>
      <style>
         label {
            float: left;
            width: 120px;
         }  
         p { clear: both; } 
      </style>
   </head>
   <body>
      <form id="formulir" action="">
         <fieldset>
            <legend>change background:</legend>
            <p>
               <label>color:</label>
               <input type="color" id="color1" name="color1">
            </p>
            <input type="submit"  id="button" value="Process">
         </fieldset>
      </form>
   </body>
</html>

1 个答案:

答案 0 :(得分:0)

您正在阻止发送表单,因此我猜您不希望重新加载该页面。这意味着你必须使用AJAX。由于您使用的是纯JavaScript,我也会使用它,但我建议使用基本项目的框架:)

在您的javascript脚本中添加类似

的内容
function sendPostToPHP( color ){
    if (window.XMLHttpRequest) var ajaxPostRequest = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari 
      else var ajaxPostRequest = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5   

    ajaxPostRequest.open("POST", "YOURSCRIPT.php", false);

    ajaxPostRequest.onreadystatechange = function() {
        if(ajaxPostRequest.readyState == 4) {
            if (ajaxPostRequest.status == 200) {
                //data was revived successfully.
            }
        }
    }

    var data = "color=" + color;
    //setting header is important - otherwise PHP will not load it into $_POST:
    ajaxPostRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    ajaxPostRequest.send(data);        
}

然后在您的行var color1 = document.getElementById("color1").value;之后添加类似:

sendPostToPHP(color1);

您的PHP可能如下所示:

if( empty($_POST['color']) ) exit("No color recived.");

try {
    $db_connection = new PDO('mysql:host=YOURHOSTNAME;dbname=YOURDBNAME', 'YOURDBUSER', 'YOURDBPASSWORD');
    $db_connection -> query("SET NAMES 'utf8'"); //optional
} catch (Exception $e) {
    // DB CONNECTION ERROR
} 
//example query:
$query = $db_connection->prepare( "INSERT INTO colors (color) VALUES (:color)" ); 
$query->bindValue(':color', $_POST['color'], PDO::PARAM_STR); 
$query->execute();

已编辑&amp;检测过

我已经更正了代码并对其进行了一些测试 - 现在可以使用了:)