使用Datatables AltEditor请求的未知参数

时间:2019-07-02 17:01:53

标签: ajax flask datatable jquery-datatables-editor

尝试更新行时,我在Datatable AltEditor上遇到了麻烦。

顺便说一句,我正在使用flask作为后端。

这是我的设置:

首先,我将向您展示数据表的外观

Datatables example

HTML表:

<div id='contenidoBienvenida'>
    <table class="dataTable table table-striped" id="example" style="width: 100%">

    </table>
</div>

瓶径:

@app.route('/getProfesores') #This route sends the json data with all the teachers
def getProfesores():
    if 'numEmpleado' in session:
        try:
            cur = mysql.connection.cursor()
            cur.execute("SELECT * FROM usuarios")
            r = [dict((cur.description[i][0], value)  # IF NULO hacer algo
                      for i, value in enumerate(row)) for row in cur.fetchall()]
            if (len(r) == 0):
                return "No hay profesores"
            return json.dumps({'data': r})
        except Exception as e:
            print(str(e))
    return redirect(url_for('home'))


#This route receives the desired data to be edited, saves changes and returns new data as JSON
@app.route('/editar/profesor/', methods=['GET']) 
def editarProfesor():
    if 'numEmpleado' in session:
        try:
            numEmpleado = request.args.get('NumEmpleado')
            nombre = request.args.get('nombre')
            password = request.args.get('password')
            correo = request.args.get('correo')
            tipoCuenta = request.args.get('tipoCuenta')
            perfilCompletado = request.args.get('perfilCompletado')

            cur = mysql.connection.cursor()
            query = "UPDATE usuarios SET NumEmpleado = %s, nombre = %s, password = %s, correo = %s, tipoCuenta = %s, perfilCompletado = %s WHERE NumEmpleado = %s"
            cur.execute(query, (numEmpleado,nombre,password,correo,tipoCuenta,perfilCompletado,numEmpleado))
            mysql.connection.commit() #Execute the update sql

            cur.execute( #Now it grabs the edited row
                "SELECT * FROM usuarios WHERE usuarios.NumEmpleado=%s" %
                numEmpleado)
            r = cur.fetchone()
            cur.close()
            return json.dumps({'data': r}) #sends the edited row as JSON -- SUCCESS
        except Exception as e:
    return redirect(url_for('home'))

profesoresDatatable.js:

$(document).ready(function() {

  var columnDefs = [{
    data: "NumEmpleado",
    title: "Número Empleado",
  },
  {
    data: "nombre",
    title: "Nombre"
  },
 {
    data: "password",
    title: "Password"
  },
 {
    data: "correo",
    title: "Mail"
  },
 {
    data: "tipoCuenta",
    title: "Tipo Cuenta"
  },
 {
    data: "perfilCompletado",
    title: "¿perfilCompletado?"
  }];

  var myTable;

  // local URLs are not allowed
  var url_ws_mock_get = './getProfesores'; #Flask route which fill the datatable
  var url_ws_mock_ok = './mock_svc_ok.json'; #not used

  myTable = $('#example').DataTable({
    "sPaginationType": "full_numbers",
    destroy: true,
    responsive: true,
    ajax: {
        url : url_ws_mock_get, #Flask route to obtain json data
        // our data is an array of objects, in the root node instead of /data node, so we need 'dataSrc' parameter
        dataSrc : 'data'
    },
    columns: columnDefs,

        dom: 'Bfrtip',        // Needs button container
        select: 'single',
        responsive: true,
        altEditor: true,     // Enable altEditor
        buttons: [{
            text: 'Agregar',
            name: 'add'        // do not change name
        },
        {
            extend: 'selected', // Bind to Selected row
            text: 'Editar',
            name: 'edit'        // do not change name
        },
        {
            extend: 'selected', // Bind to Selected row
            text: 'Borrar',
            name: 'delete'      // do not change name
        },
        {
            text: 'Refrescar',
            name: 'refresh'      // do not change name
        }],
        onAddRow: function(datatable, rowdata, success, error) {
            $.ajax({
                // a tipycal url would be / with type='PUT'
                url: url_ws_mock_ok,
                type: 'GET',
                data: rowdata,
                success: success,
                error: error
            });
        },
        onDeleteRow: function(datatable, rowdata, success, error) {
            $.ajax({
                // a tipycal url would be /{id} with type='DELETE'


   url: url_ws_mock_ok,
            type: 'GET',
            data: rowdata,
            success: success,
            error: error
        });
    },
    onEditRow: function(datatable, rowdata, success, error) { 
        $.ajax({
            // a tipycal url would be /{id} with type='POST'
            url: './editar/profesor/', #flask route which save changes and returns edited row as JSON
            type: 'GET',
            data: rowdata,
            success: success,
            error: error
        });
    }
  });


});

在以下示例中,我将名为Arturo Casanova的用户的密码从“ 123”更改为“密码”

enter image description here

完成编辑后,单击“保存更改”,将收到有关请求的未知参数的警告。

enter image description here

关闭警告后,我会收到成功消息

enter image description here

但是编辑后的行未正确插入

enter image description here

如果单击“刷新”按钮(“刷新”按钮),它将正确显示在数据表上

enter image description here

这是current JSON obtained by Flask Route'/getProfesores')

这是JSON response after editing the row,现在应该出现在数据表中

这是我正在使用的脚本

<!--SCRIPTS-->
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <script type="text/javascript"
    src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.18/b-1.5.6/b-colvis-1.5.6/b-flash-1.5.6/b-html5-1.5.6/r-2.2.2/sl-1.3.0/datatables.min.js"></script>
  <script src="{{url_for('static', filename='js/dataTables.altEditor.free.js')}}"></script>
  <script src="{{url_for('static', filename='js/profesoresDatatable.js')}}"></script>

3 个答案:

答案 0 :(得分:0)

让它正常工作

我更改了dataTables.altEditor.free.js的第285行

that._editRowCallback( data ,b,c,d,e); 更改为那个。_editRowCallback( rowDataArray ,b,c,d,e);

完整部分:

that.onEditRow(that,
                    rowDataArray,
                    function(data,b,c,d,e){ that._editRowCallback(rowDataArray,b,c,d,e); },
                    function(data){ that._errorCallback(data);
                });

现在它不显示警告,并且会按照应有的方式刷新

答案 1 :(得分:0)

我知道这是不久前发布的,但我会回复,因为我遇到了完全相同的问题,也因为我与 altEditor 的开发人员取得了联系,他们在下面回复了有关建议修复的评论。

>

修复工作的原因是它使用浏览器发送到服务器的 JSON,并且它是有效的 JSON。

如果没有建议的修复,编辑器将使用您的服务器返回的 JSON,我想您会发现这就是问题所在。只要您的服务器为表中的每一列返回带有键/值对的有效 JSON,它就会起作用。

举个例子,这是我的表:

Example table

在 onEditRow 调用的函数中,我创建了一个包含键和值的字符串,然后将其编码为 JSON 并返回:

$row = '{"client_number": "1", "name": "Mark", "phone": "89797979", "link": "http://someserver.com"}';
echo json_encode($row);

使用该代码,当我单击任何行上的编辑按钮时,它将显示表格中的记录。当我单击关闭编辑对话框时,表中的行将更改以显示我返回的 $row。如果您尝试这样做,应该足以证明使用包含每列值的有效 JSON 编辑器可以工作。

当我在浏览器中查看它从对服务器的调用接收到的内容时,它显示:

Browser Network Tab

最后,这是关闭编辑对话框后的表格。它显示了我返回的记录:

enter image description here

显然,您的服务器功能需要处理点击的实际记录并从中生成 $row。

答案 2 :(得分:0)

我知道这有点旧,但根据 github 上的文档,Mark 的答案似乎是正确的。

<块引用>

AJAX 设置

数据表接受以下回调函数作为参数:

onAddRow(alteditor, rowdata, 成功, 错误) onEditRow(alteditor, rowdata, 成功, 错误, originalrowdata) onDeleteRow(alteditor, rowdata, success, error)

在最常见的情况下,这些函数应该按预期调用 $.ajax 通过网络服务。成功和错误这两个函数应该是 作为参数传递给 $.ajax。

在程序onAddRow、onEditRow、onDeleteRow中,可以访问 使用 alteditor.s.dt 的数据表对象。

Webservice 必须以 JSON 格式返回修改后的行,因为 success() 函数期待这一点。否则你必须自己写 success() 回调(例如刷新整个表格)。

需要有一个匹配的 JSON 响应和修改后的数据来本地更新记录