无需刷新即可更改mysql数据和div内容

时间:2014-01-05 11:26:13

标签: javascript php jquery mysql ajax


我的网页上需要一个简单的状态/通知系统。
基本上我想用一个带有combobox(有三个选项)和一个提交按钮的小表单。根据选项的选择,我希望它显示各种消息(我猜需要一些php / jquery)。这些消息在刷新后应该保持不变(所以我想我需要在某处存储信息,这是最后一个选定的选项,并执行一些if语句)。我还需要它为任何用户工作而不刷新(我发现我应该在这里使用AJAX) 以下代码是我的实验效果,它们可能看起来非常混乱 此外,以下解决方案通常可用于不同用户的动态更改。刷新后他会看到新消息 提前谢谢。
 这就是我所拥有的:

的index.php:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <div class="ann">
            <?php
                $con = mysql_connect("localhost","username","password") or die('Error while connecting to db server'); ;
                mysql_select_db("test",$con) or die('Error while selecting db'); ;
    // Check connection

                $zap = "SELECT mode FROM mode";
                $result = mysql_query($zap, $con);
                $current_id = mysql_fetch_row($result);
                $current_id = $current_id[0];

                if ($current_id == 1) {
                    echo "current id equals 1";
                }
                else if ($current_id == 2) {
                    echo "current id equals 2";
                } 
                else if ($current_id == 3) {
                    echo "current id equals 3";
                }

            ?>

        </div>

        <form method="post" id="asd">
            <select name="sel">
                <option value="1">one</option>
                <option value="2">two</option>
                <option value="3">three</option>
            </select>
            <input type="submit" value="OK" id="sub" />
        </form>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>     
        <script type="text/javascript" src="func.js"></script>

    </body>
</html>

process.php:

<?php
   require "MyConnect.php"; 
   connection();
   $option = isset($_POST['sel']) ? $_POST['sel'] : false;
   if($option) {
        echo htmlentities($_POST['sel'], ENT_QUOTES, "UTF-8");
   } else {
        echo "task option is required";
        exit; 
   }
   $zapp = "UPDATE mode SET mode = '".$option."'";
   $idzapp = mysql_query($zapp);
?>

MyConnect.php:

<?php     
function connection() { 
    $mysql_server = "localhost"; 
    $mysql_admin = "username"; 
    $mysql_pass = "password"; 
    $mysql_db = "test"; 
    @mysql_connect($mysql_server, $mysql_admin, $mysql_pass) 
    or die('Error while connecting to db server'); 
    @mysql_select_db($mysql_db) 
    or die('Error while connecting to db'); 
} 
?>

func.js:

$("#asd").submit(function() {

    var url = "process.php";

    $.ajax({
           type: "POST",
           url: url,
           data: $("#asd").serialize(),
           success: function(data)
           {
           $('.ann').html(data);
           }
         });

    return false;
});

0 个答案:

没有答案