从PHP传递JQPlot的值

时间:2013-10-14 16:36:50

标签: javascript php jqplot

作为一名新手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);
?>

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

$.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函数。