Javascript 从PHP传递JQPlot的值
作为一名js和jqplot程序员的新手,我需要关于将值数组从php传递到外部javascript进行绘图(使用jqplot)的指导。我对html、php和外部js、jqplot的顺序和调用方式感到困惑。一个简短的示例代码结构将非常有帮助。我们可以使用以下示例代码作为指导。谢谢Javascript 从PHP传递JQPlot的值,javascript,php,jqplot,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'}); }); 我希望
$(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);
?>
您有几种选择。以下是两个最简单的方法:
添加
var myData=代码>位于页面顶部,然后使用myData
代替数据数组
最好的方法是使用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>
这应该行得通。
请记住,我不知道您的表单是什么样子的,这只是一个虚拟示例,但它应该足够相似。使用jQuery的.val()方法获取表单值,然后将这些值提供给ajax函数。谢谢。我遇到了一个障碍:当我使用上面的ajax.js时,如下所示:我更新了我的答案,解释了如何从表单中获取值并将它们提供给仍然不工作的ajax函数。。刚刚尝试了以下代码片段:$(document).on('click','#submitButton',function(){alert(“clicked the submitButton”);});以及在第一行获取“预期对象”错误。再次感谢。我还将包含上述代码的外部.js文件作为脚本src包含在html标题中。。。忘记包含jquery.min.js和其他源文件。。。仍在学习格式。。谢谢……)更新:作为下一步,尝试从php回显变量“start”和“end”,只是为了在将任何值传回js之前看看这是否有效。这不起作用,因为我在单击“提交”后仍停留在同一页面。
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);
});