简体   繁体   English

表单发布后填充Jquery数据表

[英]Jquery Datatables populate after form post

I'm trying to do a form submit (POST) with some parameters and based on the parameters I want to populate my datatable. 我正在尝试使用一些参数进行表单提交(POST),并根据我想要填充数据表的参数。 But I'm not very good with Javascript (My language is Java), so I'm trying to do it with an Ajax call. 但我对Javascript(我的语言是Java)不是很了解,所以我试图用Ajax调用来做。 But it won't work for me. 但它对我不起作用。 Everything works for me, except doing a POST with parameters to the servlet. 一切都适合我,除了用servlet参数POST。 The datatable always populate automatically, but it should populate after the form submit. 数据表总是自动填充,但应在表单提交后填充。

Does someone know an example of my case? 有人知道我的案例吗? I read a lot of form posts here and tutorials, but none of this case (?). 我在这里阅读了很多表格帖子和教程,但没有这种情况(?)。

My code is now as follows, this works for me. 我的代码现在如下,这对我有用。 Except I can't sort or search anymore in this table. 除了我不能在此表中排序或搜索。 What is missing? 什么东西少了?

Thank you. 谢谢。

<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>

Ok, this is the full answer for you question 好的,这是你问题的完整答案

You need to make three events, the first load the database information in your datatable, the second event inserts the new information on the database, and the third refresh the datatable content. 您需要创建三个事件,第一个事件在数据表中加载数据库信息,第二个事件在数据库中插入新信息,第三个事件刷新数据表内容。

<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>

Here the data is passed as string(formData) in ajax function and by default ajax expect the json object. 这里数据作为字符串(formData)传递到ajax函数中,默认情况下ajax期望json对象。 Passing data in string can be done in two ways 以字符串形式传递数据可以通过两种方式完成

1) Append the generated query string to the url 1)将生成的查询字符串附加到URL

     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) when data is already serialized into string then set processData flag to false in ajax 2)当数据已经被序列化为字符串时,然后在ajax中将processData标志设置为false

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

I have the same functionality as you. 我有与你相同的功能。 The way I approach things though is a little bit different. 我处理事情的方式有点不同。

What I do ... 我所做的 ...

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

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

On document.ready I call the ajax function to get me the datatable passing the value of searchCondition to my servlet. 在document.ready上我调用ajax函数来获取将searchCondition的值传递给我的servlet的数据表。 The result (THIS IS JUST THE TABLE) is put in the ajaxDataTable div. 结果(这只是表)放在ajaxDataTable div中。 On success of the ajax command, I do the normal initializations on the datatable. 在ajax命令成功后,我对数据表执行常规初始化。

Now on any search, I call the same ajax command and pass again the search condition. 现在在任何搜索中,我调用相同的ajax命令并再次传递搜索条件。

Works fine for me! 对我来说工作正常!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM