24h購物| | PChome| 登入
2013-11-04 08:08:21| 人氣2,554| 回應1 | 上一篇 | 下一篇

[Javascript] SQL & Website

推薦 0 收藏 0 轉貼0 訂閱站台




開始學習使用 MySQL 以及使用 .php 連接至資料庫進行操作。



home.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Design Portfolio Template</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
        <script type='text/javascript' src='http://vectorart.org/wp-content/themes/vector/images/jquery.js'></script>
        <script type="text/javascript" src="soapCommu.js"></script>
        <script type='text/javascript' src='https://www.google.com/jsapi'></script>
        <script type='text/javascript' src='MaintenanceService.js'></script>
</head>

<body>


<div id="top">
    <div id="insidetop">
        <h4>Drop Down Menu</h4>
       
        <p>Information Buliding</p>
       
        <h5><a href="#">Button Buliding</a></h5>
        <h5><a href="#">Button Buliding</a></h5>
        <h5><a href="#">Button Buliding</a></h5>
        <h5><a href="#">Button Buliding</a></h5>
       
    </div><!--insidetop-->
</div><!-- top -->

<div id="topline">   
    <div class="content">
       <a><strong>YOUR SITE</strong> Menu</a>
    </div>
</div><!-- topline -->


<div id="wrapper">
        <div class="content">       
             <div id="header">            
                    <h1><a href="#"><span>NCU</span>MaintenanceService</a></h1>
                     <div id="menu">
                        <ul>   
                            <li class="selected"><a href="home.php">MaintenanceService</a></li>
                            <li><a href="BoardInformation.php">BoardInformation</a></li>
                            <li><a href="SystemInformation.php">SystemInformation</a></li>
                            <li><a href="#">contact us</a></li>
                        </ul>
                   
                    </div><!-- menu -->
               
             </div><!--header-->
            
               <div class="sidebar">
                <p class="block">HW1 縮放表單</p>
                <p class="block">HW2 AJAX 簡易練習</p>
                <p class="block">HW3 AJAX - Web service 練習</p>
                <p class="block">HW4 google API 表格套用</p>
                <p class="block">HW5 SQL and web site</p>
             </div><!--sidebar-->
            
             <div id="container">
                 <div class="block" id="googleAPIBlock1"></div>
                <div class="block" id="googleAPIBlock2"></div>
                <div class="block" id="googleAPIBlock3"></div>
               
                <script type="text/javascript">
                  commu_service("SEMA_MaintenanceService", "getState", "getStateBlock", []);
                  commu_service("SEMA_MaintenanceService", "getNumOfComponents", "getNumOfComponentsBlock", []);
                  commu_service("SEMA_MaintenanceService", "getComponentInfo", "getComponentInfoBlock", []);
                </script>       
                <h2>getState()</h2>
                    <div id="content">
                        <p class="block" id="getStateBlock"></p>
                    </div>
                <h2>getNumOfComponents()</h2>
                    <div id="content">
                        <p class="block" id="getNumOfComponentsBlock"></p>
                    <div>
                <h2>getComponentInfo()</h2>
                    <div id="content">
                        <p class="block" id="getComponentInfoBlock"></p>
                    <div>      
            </div><!--container-->                       
                           
        </div><!--content-->
       
    </div><!--wrapper-->
   
<div id="footer">
        <div class="content">
               
                 <div class="sidebar">
                  
                           <a href="#"><img src="images/footerbox.png" alt="" border="0" /></a>
                        <a href="#"><img src="images/footerbox.png" alt="" border="0" class="noright" /></a>
                  
                   </div><!--sidebar-->
               <div id="left">
                <h3>SPONSORSHIP FRIENDS</h3>
                    <p><a href="#">Website Templates</a></p>
                    <p><a href="#">Website Builder</a></p>
                    <p><a href="#">Web design</a></p>
                    <p><a href="#">Powerpoint Templates</a></p>
                    <p><a href="#">Hosting Reseller</a></p>
                    <p><a href="#">Dedicated Server Hosting</a></p>
                 </div><!--left-->  
                
                 <div id="right">  
                 <h3>OUR RESOURCE SITES</h3>
                    <p><a href="#">Branding and Identity </a></p>
                    <p><a href="#">Nature Based CSS Gallery </a></p>
                    <p><a href="#">Free Vector Illustrations</a></p>
                    <p><a href="#">Organic Web Design</a></p>
                    <p><a href="#">Web Design</a></p>
                    <p><a href="#">West Coast Clothing Co</a></p>
                   </div><!--right-->
                  
                   <a href="#"><span class="leftp">copyright 2010 your comapny name</span></a>
                 
                   <a href="http://vectorart.org"><span class="rightp"> Thanks to VectorArt</span></a>
                  
                  
                 </div><!--content-->
                       
</div><!--footer-->   
   
<script type='text/javascript'>
$(document).ready(function(){

    $("div#topline a").click(function(){
      $("#top").slideToggle("slow");
      $(this).toggleClass("active");
    });       

});       
</script>   
</body>
</html>



MaintenanceService.js

對 home.php 上的圖表 javascript 進行顯示用,途中會調用 soapCommu.js 與 server 查詢 SQL。

document.write ("<script type='text/javascript' src='https://www.google.com/jsapi'></script>");
document.write ("<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>");
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawGaugeChart);
var gaugeData;
var gaugeChart;
var gaugeOptions;
function drawGaugeChart() {
    gaugeData = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['CPU Temp', 50]
    ]);

    gaugeOptions = {
            width: 800, height: 240,
            redFrom: 90, redTo: 100,
            yellowFrom:75, yellowTo: 90,
            minorTicks: 5
    };

    gaugeChart = new google.visualization.Gauge(document.getElementById('googleAPIBlock1'));
    gaugeChart.draw(gaugeData, gaugeOptions);
}
//----------------------------------------------------------
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawCoreChart);
var coreChart;
var coreOptions;
var coreData;
var coreDataArr = new Array(100);
coreDataArr[0] = ['Timestamp', 'CPU1'];
for(var i = 1; i < 100; i++) {
    coreDataArr[i] = ['', 1];
}
function drawCoreChart() {
    coreData = google.visualization.arrayToDataTable(coreDataArr);
    coreOptions = {
            title: 'CPU temperature monitoring',
            hAxis: {title: '',  titleTextStyle: {color: '#333333'}},
            vAxis: {minValue: 0},
            fontName : 'georgia', backgroundColor : "Tan"
    };
    coreChart = new google.visualization.AreaChart(document.getElementById('googleAPIBlock2'));
    coreChart.draw(coreData, coreOptions);
}
//--------------------------------------------------------
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawDonutChart);
var donutData;
var donutDataArr;
var donutOptions;
var donutChart;
donutDataArr = [['STATE', 'XX'],['SEMA_SERVICE_NOT_FOUND', 1],['SEMA_SERVICE_STOP', 1],['SEMA_SERVICE_ON', 1]];
function drawDonutChart() {
    donutData = google.visualization.arrayToDataTable(donutDataArr);
    donutOptions = {
        title: 'Service State',
        pieHole: 0.4, backgroundColor : "Tan"
    };
    donutChart = new google.visualization.PieChart(document.getElementById('googleAPIBlock3'));
    donutChart.draw(donutData, donutOptions);
}
//----------------------------------------------------
var myClock = setInterval(function(){myTimer()}, 1000);
function myTimer() {
        var lastData = gaugeData.getValue(0, 1);
        var updateData = lastData;
        if(Math.random() < 0.5)
            updateData += Math.random()*10;
        else
            updateData -= Math.random()*6;
        if(updateData > 100)
            updateData -= 20;
        if(updateData < 0)
          updateData += 50;
        gaugeData.setValue(0, 1, Math.floor(updateData));
        gaugeChart.draw(gaugeData, gaugeOptions);
//----------------------------------------------------------
        for(var i = 0; i < coreData.getNumberOfRows()-1; i++) {
            coreData.setValue(i, 1, coreData.getValue(i+1, 1));
        }
        coreData.setValue(coreData.getNumberOfRows()-1, 1, Math.floor(updateData));
        coreChart.draw(coreData, coreOptions);
//----------------------------------------------------------
/*for(var i = 0; i < donutData.getNUmberOfRows(); i++) {
  donutData.setValue(i, 1, queryResultCount(donutData.getValue(i, 0)));
}
donutChart.draw(donutData, donutOptions);*/
        //https://developers.google.com/chart/interactive/docs/reference#DataTable_setValue
}
var myClock2 = setInterval(function(){myTimer2()}, 1000);          
function myTimer2() {
    for(var i = 0; i < donutData.getNumberOfRows(); i++) {
      var count = queryResultCount("RCI:SERVICESTATUS", donutData.getValue(i, 0));
      donutData.setValue(i, 1, count);
    }
    donutChart.draw(donutData, donutOptions);
    clearInterval(myClock2);
    //https://developers.google.com/chart/interactive/docs/reference#DataTable_setValue
}

soapCommu.js

一堆 ajax 集成。

queryResultCount() 會調用 readSQL.php,請設定 async : false,等待 ajax 回傳值,
否則會一直回傳 0。


queryResultInsert() 會調用 writeSQL.php

function serviceArgvXML(ser_class_name, ser_name, req_arr) {
    var data;
    data = '<?xml version="1.0" encoding="utf-8"?>';
    data += '<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">';
    data += '<soapenv:Header/><soapenv:Body>';
    data += '<ns:' + ser_name + ' xmlns:ns="http://ws.apache.org/axis2/services/' + ser_class_name + '">';
    if(req_arr != null) {
        for(var i = 0; i < req_arr.length; i++)
            data += '<ns:' + req_arr[i].ns_id + '>' + req_arr[i].par + '</ns:' + req_arr[i].ns_id + '>';
    }
    data += '</ns:'+ser_name+'>';
    data += '</soapenv:Body>';
    data += '</soapenv:Envelope>';
    return data;
}
function commu_service(ser_class_name, ser_name, td_name, req_arr) {
    var URL = "http://140.115.53.57/axis2/services/" + ser_name;
    $.ajax({
        type : "POST",
        url : URL,
        data : serviceArgvXML(ser_class_name, ser_name, req_arr),
        contentType : "application/soap+xml",
        dataType : "xml",
        success : function(msg, status, req){
            set_td_content(td_name, req);
        },
        error : function(msg){
            alert("error" + msg);
        }
    });
}
function set_td_content(td_name, req) {
    //console.info(req.responseText);
    var data = $(req.responseText)[0]["children"][0]["children"][0]["children"];
    $("#" + td_name).empty();// clear.
    //data["childNodes"][0] -> soapenv:envelop
    //data["childNodes"][0]["childNodes"][0] -> soapenv:body
    //data["childNodes"][0]["childNodes"][0]["childNodes"][0] -> rci:getstate   SEMA_OK or SEMA_FAIL
    if(data[0]["outerText"] == "SEMA_OK") {
        for(var i = 1; i < data.length; i++) {
            if(i > 1)
               $("#" + td_name).append("<br>");
            $("#" + td_name).append(data[i].tagName +":"+ data[i]["outerText"]);
            queryResultInsert(data[i].tagName, data[i]["outerText"]);
        }
    }
    else {
       $("#" + td_name).append(data[0]["outerText"]);
    }
}          
function queryResultInsert(key, value) {
    var arr = {};
    arr[key] = value;
    $.ajax({
        type: "GET",
        url: "writeSQL.php",
        data : arr,
        success: function(data) {
        },
        error : function(data) {
            alert("Insert error");
        }
    });
}
function queryResultCount(key, value) {
    var arr = {};
    arr[key] = value;
    var result = "0";
    $.ajax({
        type: "GET",
        url: "readSQL.php",
        data : arr,
        async : false,
        success: function(msg) {
            result = msg;
        },
        error : function(data) {
            return 0;
        }
    });
    return parseInt(result);
}

readSQL.php

查詢符合欄位的個數指令

SELECT COUNT(`$key`) FROM `MorrisTest` WHERE `$key` = '$value'


<?php
    foreach($_GET as $key => $value){
        insertSQL($key, $value);
    }
    function insertSQL($key, $value) {   
        $SERVER = "localhost";
        $USER = "root";
        $PASSWORD = "--------------------";
        $con = mysql_connect($SERVER, $USER, $PASSWORD);
        $dbName = "ncu3";
        $tableName = "`MorrisTest`";
        if (!$con) {
            die('Could not connect: ' . mysql_error());
        } else {
            //echo "success link $SERVER";
            $db_selected = mysql_select_db($dbName, $con);
            if(!$db_selected) {
                die ("Can\'t use $dbName : " . mysql_error());
            } else {
                //echo "success link $dbName";
                $sqlCommand = "SELECT COUNT(`$key`) FROM `MorrisTest` WHERE `$key` = '".$value."'";
                //echo $sqlCommand;
                $result = mysql_query($sqlCommand);
                while($row = mysql_fetch_array($result)) {
                    echo $row['COUNT(`RCI:SERVICESTATUS`)'];
                }
                //echo $result;
            }
        }
        mysql_close($con);
    }
?>

writeSQL.php

插入欄位指令

INSERT INTO `MorrisTest` (`$key`) VALUES ('$value')

為了節省少開一個表單,可能會導致很多資料欄位為空。


<?php
    foreach($_GET as $key => $value){
        insertSQL($key, $value);
    }
    function insertSQL($key, $value) {   
        $SERVER = "localhost";
        $USER = "root";
        $PASSWORD = "----------------------";
        $con = mysql_connect($SERVER, $USER, $PASSWORD);
        $dbName = "ncu3";
        $tableName = "`MorrisTest`";
        if (!$con) {
            die('Could not connect: ' . mysql_error());
        } else {
            //echo "success link $SERVER";
            $db_selected = mysql_select_db($dbName, $con);
            if(!$db_selected) {
                die ("Can\'t use $dbName : " . mysql_error());
            } else {
                //echo "success link $dbName";
                $sqlCommand = "INSERT INTO `MorrisTest` (`".$key."`) VALUES ('".$value."')";
                $result = mysql_query($sqlCommand);
            }
        }
        mysql_close($con);
    }
?>

台長: Morris
人氣(2,554) | 回應(1)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 教育學習(進修、留學、學術研究、教育概況) | 個人分類: [學習]JavaScript |
此分類上一篇:[Javascript] google API 表格套用

طراحی سایت تهران سایت دیزاین
طراحی سایت یکی از خدمات اصلی شرکت طراحی سایت تهران سایت دیزاین می باشد، سئو و طراحی وب سایت حرفه ای با وردپرس
2019-03-30 15:07:29
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文