繁体   English   中英

从PHP传递JQPlot的值

[英]Passing values for JQPlot from PHP

作为js和jqplot的新手程序员,我需要有关将值数组从php传递到外部JavaScript进行绘图的指南(使用jqplot)。 我对顺序以及如何调用html,php和外部js,jqplot感到困惑。 简短的示例代码结构将非常有帮助。 我们可能使用以下示例代码作为指导。 谢谢

$(document).ready(function(){
  var plot1 = $.jqplot ('chart1',[[3,7,9,1,4,6,8,2,5]],{title: 'Plot'});
});

而不是上面的固定数据点,我希望它们通过数组从以下php脚本动态加载。

<?php
  $Start_Value = $_POST['Start'];
  $End_Value = $_POST['End'];

  for($i=$Start_Value;$i<=$End_Value;$i+++)
     $Plot_Val[$i] = $i + 2;
  json_encode($Plot_Val);
?>

您有几种选择。 这是最简单的两个:

  1. 只需将数组作为PHP全局变量从PHP中“粘贴”即可。
    添加<script>var myData = <%= json_encode($Plot_Val); %>;</script> <script>var myData = <%= json_encode($Plot_Val); %>;</script>在页面顶部,然后使用myData代替数据数组。
  2. 更好的选择是使用Ajax从JavaScript调用PHP页面并获取结果,分离前端和后端代码。

最好的方法是使用AJAX,在JS中是这样的:

$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
  console.log(response) // check what kind of stuff you got back :)
  var values = JSON.parse(response);
  // do stuff with this data
}
});

更新:要从表单获取值,您不能将表单操作应用于js,而只能使用js从表单获取值。 因此,表单本身不应该执行POST请求,而是js应该从表单中获取值并发送POST。

像这样:

<form>
<input type="text" id="start">
<input type="text" id="end">
<button id="submitButton">Submit Me!</button>
</form>

JS,我们将上面的AJAX代码包装成一个函数:

function submitValues(startValue, endValue) {
  $.ajax({
  type:'POST',
  url:'path/to/your.php',
  data: {start: startValue, end: endValue}, //passing params to php
  success: function (response) {
    console.log(response) // check what kind of stuff you got back :)
    var values = JSON.parse(response);
    // do stuff with this data
  }
  });
}

$(document).on('click', '#submitButton', function(){
  var start = Number($('#start').val());
  var end = Number($('#end').val());
  //I guess you need numbers instead of text, that's why they are wrapped inside Number()
  submitValues(start, end);
});

这应该工作。 请记住,我不知道您的表单是什么样子,这只是一个虚拟的示例,但应该足够相似。 您可以使用jQuery的.val()方法获得表单值,然后将这些值提供给ajax函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM