2013-08-12 5 views
0

질문부터 시작하겠습니다 : MySql DB를 쿼리하는 PHP 파일이 있습니다. 결과를 플롯 할 수 있도록 자바 스크립트 배열에 넣고 싶습니다. jQuery의 flot 사용). 아무도 그걸 어떻게 할 생각이 있습니까? 지금까지 작동하는 짓을했는지 어떤PHP 파일에서 자바 스크립트 변수로 데이터를 가져 오는 방법

는 :

  1. 나는 차트를 나타내는 아주 좋은 jQuery를-FLOT 코드가 있습니다. 이 코드에서이 질문의 가장 중요한 변수는 "data1"입니다.
  2. 내가 (JQuery와-FLOT 코드)은 "DATA1"변수에 넣을

, 데이터 데이터베이스에서 MySQL 데이터베이스에서 데이터를 출력 (PHP 파일 포함)

  • AJAX (시간과 데이터)하지만 나는 "데이터"변수와 PHP 파일 결과를 연결하는 방법을 찾을 수 없습니다.

    JQuery와-FLOT 차트 음모를 꾸미고 코드 (주의하시기 바랍니다 '데이터 1'변수) : 반면에

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
    
    <html> 
    <head> 
        <title>Flot Example</title> 
        <script language="javascript" type="text/javascript" src="js/flot/jquery.js"></script> 
        <script language="javascript" type="text/javascript" src="js/flot/jquery.flot.js"></script> 
        <script language="javascript" type="text/javascript" src="js/flot/jquery.flot.selection.js"></script> 
    </head> 
    <body> 
        <h1>Flot Examples</h1>s 
        <div id="placeholder" style="width:600px;height:300px"></div> 
        <div id="overview" style="width:160px;height:100px"></div> 
        <script type="text/javascript"> 
        /*Show Tooltip*/ 
        function showTooltip(x, y, contents) { 
        $('<div id="tooltip">' + contents + '</div>').css({ 
         position: 'absolute', 
         display: 'none', 
         top: y + 5, 
         left: x + 5, 
         border: '1px solid #fdd', 
         padding: '2px', 
         'background-color': '#fee', 
         opacity: 0.80 
        }).appendTo("body").fadeIn(200); 
    } 
    
    //End of Tooltip  
    var data, data1, options, optionsOverview, chart, overview; 
    var data2 = [], 
    data3 = []; 
    data1 = [ 
        [1, 4], 
        [2, 5], 
        [3, 6], 
        [4, 9], 
        [5, 7], 
        [6, 6], 
        [7, 2], 
        [8, 1], 
        [9, 3] 
    ]; 
    
    for (var i = 1; i < 10; i++) { 
        data2.push([i, i * 2]) 
    } 
    
    for (var i = 1; i < 10; i++) { 
        data3.push([i, 10 * Math.random()]) 
    } 
    
    data = [{ 
        data: data1, 
        label: "fixed", 
        lines: { 
         show: true 
        } 
    }, { 
        data: data2, 
        label: "linear", 
        lines: { 
         show: true 
        }, 
        points: { 
         show: true 
        } 
    }, { 
        data: data3, 
        label: "random", 
        bars: { 
         show: true, 
         barWidth: 0.5 
        } 
    }]; 
    
    options = { 
        legend: { 
         position: "nw" 
        }, 
        grid: { 
         clickable: true, 
         hoverable: true 
        } 
    }; 
    
    //SELECTION 
    optionsOverview = { 
        legend: { 
         show: false 
        }, 
        selection: { 
         mode: "xy" 
        } 
    }; 
    
    $(document).ready(function() { 
        chart = $.plot($("#placeholder"), data, options); 
        //SELECTION 
        overview = $.plot($("#overview"), data, optionsOverview); 
    }); 
    
    /*SELECTION*/ 
    $("#overview").bind("plotselected", function (event, ranges) { 
        chart.setSelection(ranges); 
    }); 
    
    $("#placeholder").bind("plotselected", function (event, ranges) { 
    if (ranges.xaxis.to - ranges.xaxis.from < 0.00001) { 
        ranges.xaxis.to = ranges.xaxis.from + 0.00001; 
    } 
    if (ranges.yaxis.to - ranges.yaxis.from < 0.00001) { 
        ranges.yaxis.to = ranges.yaxis.from + 0.00001; 
    } 
    plot = $.plot("#placeholder", data, 
        $.extend(true, {}, options, { 
         xaxis: { 
          min: ranges.xaxis.from, 
          max: ranges.xaxis.to 
         }, 
         yaxis: { 
          min: ranges.yaxis.from, 
          max: ranges.yaxis.to 
         } 
        }) 
    ); 
    overview.setSelection(ranges, true); 
    
    }); 
    //End of Selection 
    /*Show Tooltip*/ 
    
    $("#placeholder").bind("plothover", function (event, pos, item) { 
        $("#tooltip").remove(); 
        if (item) { 
         var x = item.datapoint[0].toFixed(2), 
         y = item.datapoint[1].toFixed(2); 
         showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " - " + y); 
        } 
    }); 
    //End of Tooltip 
    </script> 
        <br /><br /><br /> 
    
    </body> 
    </html> 
    

    내가 가지고있는 MySQL의 DB를 :

    mysql> select * from example5; 
    +------+------+ 
    | time | data | 
    +------+------+ 
    | 1 | 1 | 
    | 1 | 2 | 
    | 2 | 3 | 
    | 3 | 6 | 
    | 4 | 9 | 
    | 5 | 10 | 
    | 6 | 15 | 
    | 7 | 20 | 
    +------+------+ 
    8 rows in set (0.00 sec) 
    

    하는 나는 ajax/php 파일로 접근한다 : index.html :

    ,
    <html> 
    <head> 
    <script> 
    function showUser(str) { 
        if (str == "") { 
         document.getElementById("txtHint").innerHTML = ""; 
         return; 
        } 
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari 
         xmlhttp = new XMLHttpRequest(); 
        } else { // code for IE6, IE5 
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
        xmlhttp.onreadystatechange = function() { 
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
          document.getElementById("txtHint").innerHTML = xmlhttp.responseText; 
         } 
        } 
        xmlhttp.open("GET", "getdata.php?q=" + str, true); 
        xmlhttp.send(); 
    } 
    </script> 
    </head> 
    <body> 
    
    <form> 
    <select name="users" onchange="showUser(this.value)"> 
    <option value="">Select Time:</option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
    <option value="4">4</option> 
    <option value="4">5</option> 
    <option value="4">6</option> 
    <option value="4">7</option> 
    </select> 
    </form> 
    <br> 
    <div id="txtHint"><b>Person info will be listed here.</b></div> 
    
    </body> 
    </html> 
    

    및 getdata.php : 당신의 도움에 대한

    <?php 
    $q=$_GET["q"]; 
    
    
    $con = mysqli_connect('localhost','root','12345678','test'); 
    if (!$con) 
        { 
        die('Could not connect: ' . mysqli_error($con)); 
        } 
    
    mysqli_select_db($con,"test"); 
    $sql="SELECT * FROM example5 WHERE time = '".$q."'"; 
    
    $result = mysqli_query($con,$sql); 
    
    echo "<table border='1'> 
    <tr> 
    <th>Time</th> 
    <th>Data</th> 
    </tr>"; 
    
    while($row = mysqli_fetch_array($result)) 
        { 
        echo "<tr>"; 
        echo "<td>" . $row['time'] . "</td>"; 
        echo "<td>" . $row['data'] . "</td>"; 
        echo "</tr>"; 
        } 
    echo "</table>"; 
    
    mysqli_close($con); 
    ?> 
    

    감사합니다, 노암

  • +0

    유사한 데이터베이스는 AJAX의 대답을 JSON 대신 HTML/XML을 사용하는 것이 더 쉽습니다에 연결 한 후이 될 것입니다. PHP $ 행을 JSON 문자열로 표시하고 자바 스크립트로 문자열을 배열로 다시 디코딩합니다. 두 줄의 코드. 예 : http://www.caveofprogramming.com/php/php-json-an-example-javascript-json-client-with-php-server/ – TheBronx

    답변

    3

    PHP와 자바 스크립트 간의 통신을하는 쉬운 방법은 JSON이다. PHP는 JSON의 배열을 쉽게 인코딩/디코딩 할 수 있으며 JS는 객체를 사용하여 동일한 작업을 수행 할 수 있습니다. (내가 jQuery를 사용하고 있습니다) 당신의 자바 스크립트에서

    <?php 
        $q=$_GET["q"]; 
        $con = mysqli_connect('localhost','root','12345678','test'); 
        if (!$con) 
        { 
         die('Could not connect: ' . mysqli_error($con)); 
        } 
    
        mysqli_select_db($con,"test"); 
        $sql="SELECT * FROM example5 WHERE time = '".$q."'"; 
    
        $result = mysqli_query($con,$sql); 
    
        $returnArray = array(); 
        while($row = mysqli_fetch_array($result)) 
        { 
         $returnArray[] = array($row['time'], $row['data']); 
        } 
        echo json_encode($returnArray); 
        mysqli_close($con); 
    ?> 
    

    를,이 같은 AJAX 호출을 만들 : 당신의 PHP 스크립트에서

    데이터와 JSON 배열을 반환 : 다음을 시도 할 수 있습니다

    function retrieveResults(str){ 
    jQuery.ajax({ 
         type: 'GET', 
         url: "getdata.php", 
         data: { 
          q: str, 
         }, 
         success: function(data, textStatus, jqXHR) { 
          var json = $.parseJSON(data); 
           $.each(json, function(index, value) { 
            data1.push(value); // Not sure if it is correct, you might need to do some changes, but this is for the global idea 
           } 
         }, 
         error: function(jqXHR, textStatus, errorThrown) { 
          console.log('An error occurred:'+errorThrown); 
         } 
        }); 
    } 
    
    +0

    "$ result = array();" $ 결과를 초기화 하시겠습니까? – nerez

    +0

    그래, 지금 봤어, 나는 변수 이름에 신경 쓰지 않았다. 내 실수 야. 미안해. – noKid

    +0

    그리고 또 다른 질문인데, 'data1'이 전역 변수라고 생각합니까? 그렇지 않으면 의 javascript 섹션에서 어떻게 사용하겠습니까? – nerez

    0

    당신은 데이터베이스에서이 자바 스크립트를 출력하려고합니다. data1 = [[1,4], [2,5], [3,6], [4,9], [5,7], [6,6], [7,2], [8,1 ], [9,3]];

    코드가 .php 페이지에있는 한 javacript 행을 에코 할 수 있습니다.

    <?php echo 'data1 = ['.while($row = mysqli_fetch_array($result)){echo '['$row['time'].",".$row['data'].'],';}.'];' 
    

    당신이 getdata.php

    관련 문제