表单发布后填充Jquery数据表

时间:2013-04-08 18:22:55

标签: javascript jquery html datatables

我正在尝试使用一些参数进行表单提交(POST),并根据我想要填充数据表的参数。但我对Javascript(我的语言是Java)不是很了解,所以我试图用Ajax调用来做。但它对我不起作用。一切都适合我,除了用servlet参数POST。数据表总是自动填充,但应在表单提交后填充。

有人知道我的案例吗?我在这里阅读了很多表格帖子和教程,但没有这种情况(?)。

我的代码现在如下,这对我有用。除了我不能在此表中排序或搜索。缺少什么?

谢谢。

<script type="text/javascript" language="javascript" src="/global/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="/global/js/jquery.dataTables.min.js"></script>

<form name="myform" id="myform" action="" method="POST">  
  <label for="season">Season:</label>  
  <input type="text" name="season" id="season" value=""/> <br />
  <label for="type">Type:</label>  
  <input type="text" name="type" id="type" value=""/> <br/>
  <input type="button" id="btnSubmit" name="btnSubmit" value="Search"> 
</form>

<table class="display" id="example">
  <thead>
    <tr>
      <th>Name</th>
      <th>NationId</th>
      <th>RegionId</th>
      <th>Attendance</th>
    </tr>
  </thead>
  <tbody>
    <!-- data goes here -->
  </tbody>
</table>

<script>
  $("#btnSubmit").click( function() {
    var formData = "season=" + $("input#season").val() + "&type=" + $("input#type").val();
    $('#example').dataTable( {
      "bJQueryUI": true,
      "bProcessing": true,
      "bDestroy": true,
      "sAjaxSource": "/servlets/service/competitions/",
      "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
        oSettings.jqXHR = ${esc.d}.ajax( {
          "dataType": 'json',
          "type": "POST",
          "url": sSource,
          "data": formData,
          "success": fnCallback
          } );
      }
    } );
  } );
</script>

3 个答案:

答案 0 :(得分:12)

好的,这是你问题的完整答案

您需要创建三个事件,第一个在数据表中加载数据库信息,第二个事件在数据库中插入新信息,第三个事件刷新数据表内容。

<html>
<head>
<script type="text/javascript" language="javascript" src="/global/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="/global/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
//Global variables 
var otable;
var dataTab;
$(document).ready(function () {
    chargeData();
    $('#btnSubmit').click(function () {
       insertData();
    });   
}); 

// 1. charge all data 
function chargeData() {
    $.ajax({
        type: "POST",
        //create a method for search the data and show in datatable
        url: "/servlets/service/competitions/",
        contentType: "application/json; charset=utf-8",
        data: '{ }',
        dataType: "json",
        success: AjaxGetFieldDataSucceeded,
        error: AjaxGetFieldDataFailed
    });
}

function AjaxGetFieldDataSucceeded(result) {
    if (result != "[]") {

        dataTab = $.parseJSON(result);
        //instance of datatable
        oTable = $('#example').dataTable({
            "bProcessing": true,
            "aaData": dataTab,
            //important  -- headers of the json
            "aoColumns": [{ "mDataProp": "season" }, { "mDataProp": "type" }],
            "sPaginationType": "full_numbers",
            "aaSorting": [[0, "asc"]],
            "bJQueryUI": true,

        });

    }
}

function AjaxGetFieldDataFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

// 2. this function only insert the data in your database
function insertData() {
    var email = $("#season").val();
    var evento = $("#type").val();
    $.ajax({
        type: "POST",
        //in this method insert the data in your database
        url: "/servlets/service/competitions/",
        contentType: "application/json; charset=utf-8",
        data: '{ season : "' + season + '", type : "' + type + '"}',
        dataType: "json",
        success: AjaxUpdateDataSucceeded,
        error: AjaxUpdateDataFailed
    });
}

function AjaxUpdateDataSucceeded(result) {
    if (result != "[]") {
        alert("update ok");
        refreshDatatable();
    }
}

function AjaxUpdateDataFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

// 3. This function refresh only the datatable not all page  in varius events you can call like INSERT,UPDATE,DELETE ;D
function refreshDatatable() {
    $.ajax({
        type: "POST",
        //same event used in chargeData function
        url: "/servlets/service/competitions/",
        contentType: "application/json; charset=utf-8",
        data: '{ }',
        dataType: "json",
        success: AjaxRefreshDataSucceeded,
        error: AjaxRefreshDataFailed
    });
}

function AjaxRefreshDataSucceeded(result) {
    if (result.d != "[]") {
        var jposts = result;
        dataTab = $.parseJSON(jposts);
        //when the instance of datatable exists, only pass the data :D
        oTable.fnClearTable();
        oTable.fnAddData(dataTab);
    }
}

function AjaxRefreshDataFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

<script>
</head>
<body>
<form name="myform" id="myform" action="">  
  <label for="season">Season:</label>  
  <input type="text" name="season" id="season" value=""/> <br />
  <label for="type">Type:</label>  
  <input type="text" name="type" id="type" value=""/> <br/>
  <input type="button" id="btnSubmit" name="btnSubmit" value="Search"> 
</form>

<table class="display" id="example">
  <thead>
    <tr>
      <th>SEASON</th>
      <th>TYPE</th>
    </tr>
  </thead>
  <tbody>
    <!-- data goes here -->
  </tbody>
</table>
</body>
</html>

答案 1 :(得分:0)

这里数据作为字符串(formData)传递到ajax函数中,默认情况下ajax期望json对象。以字符串形式传递数据可以通过两种方式完成

1)将生成的查询字符串附加到网址

     oSettings.jqXHR = ${esc.d}.ajax( {
           "dataType": 'json',
           "type": "POST",
           "url": sSource + "?" + formData, /*  here url need be proper, as url can have some query string params in that case it shoukd be join with "&" not "?" */
           /* "data": formData, no need to have data config then */
           "success": fnCallback,
           "processData": false
          } );

2)当数据已经被序列化为字符串时,然后在ajax中将processData标志设置为false

oSettings.jqXHR = ${esc.d}.ajax( {
          "dataType": 'json',
          "type": "POST",
          "url": sSource,
          "data": formData,
          "success": fnCallback,
          "processData": false
          } );

答案 2 :(得分:0)

我有与你相同的功能。我处理事情的方式有点不同。

我做了什么...

<input type="text" id="searchCondition"/>

<div id="container">
  <div id="ajaxDataTable"></div> 
</div>

在document.ready上我调用ajax函数来获取将searchCondition的值传递给我的servlet的数据表。结果(这只是表)放在ajaxDataTable div中。在ajax命令成功后,我对数据表执行常规初始化。

现在在任何搜索中,我都调用相同的ajax命令并再次传递搜索条件。

对我来说很好!