簡體   English   中英

單擊時通過JQuery將表值傳遞給PHP腳本

[英]Table value passed to PHP script via JQuery when clicked

我在數據表中有一個鏈接,可以打開引導程序模式。 在模式中,我有一個morris.js圖。 我在弄清楚如何根據用戶單擊的鏈接篩選數據集時遇到麻煩。

如何讀取它們單擊的位置的值(例如,在此示例中為Cluster1或Cluster2)。 將該變量傳遞給數據提取腳本(例如cluster_pulse.php),然后傳遞給該腳本中的SQL查詢?

謝謝!!

表格的片段:

<tr class="odd">
<td class="sorting_1">
<a href="#" data-toggle="modal" data-target="#clusterpulse">Cluster1</a></td>...
<a href="#" data-toggle="modal" data-target="#clusterpulse">Cluster2</a></td>...

模態:

<div class="modal fade" id="clusterpulse" tabindex="-1" role="dialog"
                aria-labelledby="clusterpulse" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
         <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal"
         aria-hidden="true">&times;</button>
         <h4 class="modal-title" id="myModalLabel">Cluster Pulse</h4>
         </div>
         <div class="modal-body">  
         <div class="panel panel-primary">
         <div class="panel-heading">
            <h3 class="panel-title"><i class="fa fa-long-arrow-right"></i>Cluster Pulse</h3>
         </div>
         <div class="panel-body">
         <div id="morris-chart-cluster-pulse"></div>
         </div>
        </div>
        </div>
         </div>
       </div>
     </div>

js:

<script> 
        $('#clusterpulse').on('shown.bs.modal', function () {
            $(function () {
            $( "#morris-chart-cluster-pulse" ).empty();

            // Create a Bar Chart with Morris
            var chart = Morris.Line({
                element: 'morris-chart-cluster-pulse',

                d: [
                    { d: '0', VSI: 0 }
                  ],
                  xkey: 'd',
                  ykeys: ['test'],
                  labels: ['test'],
                gridIntegers: true,
                  ymax: '1',
                  ymin: '0',
                  xLabelFormat: function(d) { return (d.getMonth()+1)+'/'+d.getDate();},
                  xLabels: "week"

            });

            // Fire off an AJAX request to load the data
            $.ajax({
                type: "GET",
                dataType: 'json',
                url: "../scripts/cluster_pulse.php", // This is the URL to the API

            })
                .done(function (data) {
                    // When the response to the AJAX request comes back render the chart with new data
                    chart.setData(data);
                })
                .fail(function () {
                    // If there is no communication between the server, show an error
                    alert("error occured");
                });
        });
        });

數據提取腳本:

<?php 
include("connect.php");

if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Set up and execute the query. */
$sql = "SELECT d,test FROM <database> WHERE CLUSTER_NAME = '%$value%'
";
$stmt = sqlsrv_query( $conn, $sql);

do {
 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
 $json[] = $row;

 }
} while ( sqlsrv_next_result($stmt) );
foreach($json as &$each) {
// reassign "d" key to just the date (formatted), discard the rest
$each['d'] = date('Y-m-d', strtotime($each['d']));
}
echo json_encode($json);
?>

以下示例的HTML(我不知道您的表是否有問題):

<a href='#' data-toggle='modal' data-target='#clusterpulse' id='cluster_number_1'>Cluster1</a>
<a href="#" data-toggle='modal' data-target='#clusterpulse' id='cluster_number_2'>Cluster2</a>

AJAX

$('#cluster_number_1').click(function(){
  $.ajax({
    type:'GET',
    dataType:'JSON',
    url:'../scripts/cluster_pulse.php?cluster1='+encodeURIComponent($(this).html())+'&something_else='+encodeURIComponent("now it's url safe 1")
  }).done(/* or use success ajax Object property */);
  return false;
});
$('#cluster_number_2').click(function(){
  $.ajax({
    type:'GET',
    dataType:'JSON',
    url:'../scripts/cluster_pulse.php?cluster2='+encodeURIComponent($(this).html())+'&something_else='+encodeURIComponent("now it's url safe 2")
  }).done(/* or use success ajax Object property */);
  return false;
});

您將在../scripts/cluster_pulse.php獲得AJAX,例如:

$data = array();
if(isset($_GET['something_else'])){
  // rawurldecode($_GET['something_else']) is 'now it's url safe 1'
  if(isset($_GET['cluster1'])){
    $data = array('cluster1' = $_GET['cluster1'], $data['extra_data'] = 'some other data here 1');
    // perform database stuff here
    // $db->query(); lots more stuff assign to $data array
  }
  elseif(isset($_GET['cluster2'])){
    // rawurldecode($_GET['something_else']) is 'now it's url safe 2'
    $data = array('cluster2' = $_GET['cluster2'], $data['extra_data'] = 'some other data here 2');
    // perform database stuff here
    // $db->query(); lots more stuff assign to $data array
  }
  echo json_encode($data);
}
else{
  // a $_GET hack occurred
}

現在從內部

.done(function(results){
  /* result are now JSON with properties like:
    {
      'cluster1':'Cluster1',
      'extra_data':'some other data here 1';
    }
    or
    {
      'cluster2':'Cluster1',
      'extra_data':'some other data here 2';
    }
    Note:
      There is probably no need to send results already available in JavaScript to the
      Server only to get them back to pass the results into your `.done()` method's
      function argument
   $('#outputId1').html(results.cluster1);
  */
});

我最終要做的是將一個具有集群名稱的ID添加到表對象:

...
<td class="sorting_1">
<a href="#" data-toggle="modal" data-target="#clusterpulse" id="cluster1">cluster1</a></td>
...

然后在javascript中,我抓取了被點擊對象的ID,並將其分配給全局變量:

$("table").delegate("a", "click", function() {
id=$(this).attr('id');
}); 

然后在獲取中,將ID傳遞給API:

$.ajax({
type: "GET",
dataType: 'json',
url: "../scripts/cluster_pulse.php?val="+id, // This is the URL to the API

然后在php中,我抓取了變量並將其傳遞給查詢:

$rec = $_REQUEST['val'];
...
$sql = "SELECT d,test FROM <database> WHERE CLUSTER_NAME = ('".$rec."')";

它似乎工作正常。 感謝您的所有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM