【问题标题】:Using Datatables AltEditor requested unkown parameter使用 Datatables AltEditor 请求未知参数
【发布时间】:2019-11-13 09:03:47
【问题描述】:

我在尝试更新行时遇到Datatable AltEditor 问题。

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

这是我的设置:

首先我会告诉你数据表是什么样子的

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”更改为“密码”

当我完成编辑并单击保存更改后,我会收到有关请求的未知参数的警告。

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

但是编辑的行没有正确插入

如果我点击 Refrescar 按钮(刷新按钮),它将正确显示在数据表上

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

【问题讨论】:

    标签: ajax flask datatable jquery-datatables-editor


    【解决方案1】:

    搞定了

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

    that._editRowCallback(数据,b,c,d,e); 改为 that._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);
                    });
    

    现在它不再显示警告,而是按原样刷新

    【讨论】:

    • 感谢您反馈解决方案,这对我今晚有帮助!
    • 很高兴它能帮到你! @NathanPond
    • 恕我直言,这不是一个好的解决方案。 “rowDataArray”是浏览器发送给服务器的数据,而“data”是服务器返回给客户端的数据。这意味着您将忽略对数据的每一次服务器端修改。可能您必须更好地分析服务器返回的内容。如果你真的要忽略服务器端的东西,你应该修改传递给构造函数的函数'onEditRow'。
    【解决方案2】:

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

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

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

    例如,这是我的表:

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

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

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

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

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

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

    【讨论】:

      【解决方案3】:

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

      AJAX 设置

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

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

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

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

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

      需要与修改后的数据匹配的 JSON 响应才能本地更新记录

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-26
        • 1970-01-01
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多