使用javascript提交表单时,为什么值未定义?

时间:2012-11-22 00:34:31

标签: php javascript ajax forms google-visualization

的javascript:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
$(function() {
  //
  $('#button_submit').click(function() {
    var start_date = $('start_date').val();
    var end_date = $('end_date').val();
    var type = $('type').val();
    alert(start_date);
  });
});
// 
function drawChart() {
  var jsonData = $.ajax({
    url: "visits/day.php?start_date=" + start_date + "&end_date=" + end_date,
    dataType: "json",
    async: false
  }).responseText;

  var obj = jQuery.parseJSON(jsonData);
  var data = google.visualization.arrayToDataTable(obj);


  var options = {
    title: 'Number of visitors'
  };

  if (type === 'pie') {
    var chart = new google.visualization.PieChart(
      document.getElementById('chart_div'));
      chart.draw(data, options);
  }
  if (type === 'bar') {
    var chart = new google.visualization.BarChart(
      document.getElementById('chart_div'));
      chart.draw(data, options);
  }
}  

HTML:

<form id="myForm">
    <input type="text" name="start_date" id="start_date"><br />
    <input type="text" name="end_date" id="end_date"><br />
    <input type="text" name="type" id="type"><br />
    <input type="button" id="button_submit" value="go">
</form>
<div id="chart_div" style="width: 900px; height: 500px;"></div>

通过表单获得的变量似乎是空的,我做了那个警报(start_date)并说:unifined并且没有通过url:visits / day.php?start_date ...

我需要将这些值发送到我的php页面而不刷新页面

我做错了什么?

2 个答案:

答案 0 :(得分:2)

var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
var type = $('#type').val();

这将按id#后跟id值)找到HTML元素。

$('start_date').val();

上面会找到标签名为<start_date>

的元素

接下来,您的变量具有功能可见范围。所以它们只在匿名函数中定义(并且可见)(这是button_submit点击处理程序的回调。)

答案 1 :(得分:1)

添加到上面的内容...我不知道您将start_dateend_date传递到drawChart()函数的位置:

编辑添加对drawChart()的调用

$(function() {
  //
  $('#button_submit').click(function() {
    var start_date = $('#start_date').val();
    var end_date = $('#end_date').val();
    var type = $('#type').val();
    drawChart(start_date, end_date)
    console.log(start_date, end_date, type);
  });
});
function drawChart(start_date, end_date) {
  var jsonData = $.ajax({
    url: "visits/day.php?start_date=" + start_date + "&end_date=" + end_date,
    dataType: "json",
    async: false
  }).responseText;