使用ajax json提交并加载

时间:2012-11-21 13:41:22

标签: php jquery ajax google-visualization

的index.html:

Function drawChart() {
            var jsonData = $.ajax({
                url: "server.php",
                dataType: "json",
                async: false
            }).responseText;

            var obj = jQuery.parseJSON(jsonData);

            var data = google.visualization.arrayToDataTable(obj);

            var options = {
                title: 'Number of visitors / <?php echo $unit; ?>'
            };

            var chart = new google.visualization.BarChart(
                        document.getElementById('chart_div'));
            chart.draw(data, options);
    }       
       }

server.php:

$SQLString = "SELECT (...)'".$_POST['value']."' (...)
$result = mysql_query($SQLString);  
(...)
$data[$i] = array(...)
echo json_encode($data);

那么,index.html从server.php获取数据对吗? 我可以向server.php发送一些值,这些值在index.html执行jsonData等之前对查询很重要吗?怎么样?

谢谢:)

3 个答案:

答案 0 :(得分:1)

查询参数示例:

var jsonData = $.ajax({
                url: "server.php?someQuery=" + query,
                dataType: "json",
                async: false
            }).responseText;

答案 1 :(得分:0)

您可以通过ajax使用post方法发送。这是一个JQuery示例:

    $.ajax({
             type: "POST",
             url: "some.php",
             data: { name: "John", location: "Boston" }
          }).done(function( msg ) {
                    alert( "Data Saved: " + msg );
                  });

http://api.jquery.com/jQuery.ajax/

答案 2 :(得分:0)

您可以使用phery http://phery-php-ajax.net为您自动执行的库,在您的情况下它将是:

事件phery:json将处理从服务器发送的JSON

var remote = phery.remote('data', {'argument': 'you want to send'}, {'target':'server.php'}, false);
remote.bind('phery:json', function(event, obj){
  var data = google.visualization.arrayToDataTable(obj);

  var options = {
    title: 'Number of visitors / <?php echo $unit; ?>'
  };

  var chart = new google.visualization.BarChart(
    document.getElementById('chart_div'));

  chart.draw(data, options);
});

remote.phery('remote'); // call the remote AJAX function

server.php

function data($data){
  $r = new PheryResponse;
  // $data['argument'] will have 'you want to send'
  $SQLString = "SELECT (...)'".$_POST['value']."' (...)"
  $result = mysql_query($SQLString);  
  (...);
  $data[$i] = array(...);
  return $r->json($data); 
}

Phery::instance()->set(array(
  'data' => 'data'
))->process();