我还有一个问题:Ajax表单返回变量到php
Ajax表单运行良好。他们大多数需要做的东西,只有返回值,如果该条目可以写或不。我只用了回声。例如回声“1”;如果可以写入值并回显“2”;如果这些值不能被写入。
现在我需要回调3个变量。我知道我可以将它们写入一个数组中。我的问题是,我不能将这个变量返回到我的可见网站。
这是我的JavaScript代码:
//Show statistic
$('.statistic_submit').click(function(){
if ($('#month').val() == 'none' || $('#year').val() == 'none') {
$("#dialog_empty").dialog("open");
return false;
}
var form = $('#statistic_view');
var data = form.serialize();
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
success: function (reqCode) {
if (reqCode == 1) {
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog("open");
}
}
});
return false;
});
这是我的html代码:
<div>
<form id="statistic_view" action="include/scripts/user_statistic.php" method="post">
<select name="month" id="month">
<option value="none" class="bold italic">Monat</option>
<?php
for($i=1; $i<=12; $i++){
if($i == $month)
echo "<option value=\"".$i."\" selected>".$month_name[$i]."</option>\n";
else
echo "<option value=\"".$i."\">".$month_name[$i]."</option>\n";
}
?>
</select>
<select name="year" id="year">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2012; $i<=$year; $i++){
if($i == $year)
echo "<option value=\"".$i."\" selected>".$i."</option>\n";
else
echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<br/><br/>
<div id="user_statistic">
<input type="submit" id="small" class="statistic_submit" value="Daten anzeigen">
</div>
</form>
<br />
<div class="done">
<p class="bold center"><?php echo "Besucher ".$month_name[$month]." ".$year; ?></p>
<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>
<script>
chart = new RGraph.Line('cvs', <?php print($data_string) ?>);
chart.Set('chart.tooltips', <?php print($labels_tooltip) ?>);
chart.Set('chart.tooltips.effect', 'expand');
chart.Set('chart.background.grid.autofit', true);
chart.Set('chart.gutter.left', 35);
chart.Set('chart.gutter.right', 5);
chart.Set('chart.hmargin', 10);
chart.Set('chart.tickmarks', 'circle');
chart.Set('chart.labels', <?php print($labels_string) ?>);
chart.Draw();
</script>
</div>
</div>
这我user_statistic.php:
... (mysql stuff)
/******************************/
/** Create diagram
/******************************/
$labels = array();
$data = array();
for ($j=1; $j<=$days; $j++) {
$labels[$j] =$j;
$data[$j] = $day_value[$j];
}
// Aggregate all the data into one string
$data_string = "[" . join(", ", $data) . "]";
$labels_string = "['" . join("', '", $labels) . "']";
$labels_tooltip = "['" . join("', '", $data) . "']";
//data written
echo "1";
所以回声 “1”;告诉我的脚本,一切都很好。但现在我需要$ data_string,$ labels_string和$ labels_tooltip。那么我怎么能从user_statistic.php中返回这些值到我的身边呢?
不要忘记使用'dataType'为'json'。或者在服务器端设置标题,指定响应是json。 –
如何在PHP中处理json响应?因为必须将变量写入.done容器以显示图表。 – JPM
@JPM你不会在* PHP中处理JSON响应*。 PHP *向JavaScript发送* JSON响应。 JavaScript处理JSON数据。我在回答的底部向您展示了如何访问JSON对象的成员。 – Sampson