【问题标题】:Datatable Jquery Plugin implementation数据表 Jquery 插件实现
【发布时间】:2017-04-26 21:43:21
【问题描述】:

我不断收到来自数据表 Jq 插件的“无效 json 响应”, 我正在发布我的 webmethod 和 HTML 结构以及 AJAX 调用, 我怀疑我的 web 方法没有正确序列化为 JSON 格式,但是当我测试格式时我发现它有效 (http://jsonlint.com/)。我无法解决这里的问题

  <WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False, XmlSerializeString:=False)> _
Public Function SrcTblRegx()
    Dim constr As String = ConfigurationManager.ConnectionStrings("ARTSQLConStrng").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("TblRegSearchx", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Connection = con
            Dim ds As New DataSet()
            Using sda As New SqlDataAdapter(cmd)
                sda.Fill(ds)
            End Using
            Dim jsondata As String = JsonConvert.SerializeObject(ds)
            Return jsondata
        End Using
    End Using
End Function

Web 方法的输出是

<anyType xmlns:q1="http://www.w3.org/2001/XMLSchema" xmlns:d1p1="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/" d1p1:type="q1:string">
{"Table":[{"Filenum":15112777,"FullName":"marwam saleh moh saleem","DOB":"2015-11-26T00:00:00"}]}
</anyType>
<table id="RegSrc2" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th><b>File Number</b></th>
                                    <th><b>Patient Name</b></th>
                                    <th><b>DOB</b></th>
                                </tr>

                            </thead>
                            <tbody></tbody>
                            <tfoot>
                                <tr>
                                    <th><b>File Number</b></th>
                                    <th><b>Patient Name</b></th>
                                    <th><b>DOB</b></th>
                                </tr>
                            </tfoot>
                        </table>

 $(document).ready(function () {
                    var $table = $('#RegSrc2');
                    $table.dataTable({
                        bProcessing: true,
                        "serverSide": true,
                        "sAjaxSource": $table.data('../CONFIG/WebSerTblsSearch.asmx/SrcTblRegx'),
                    })
                });

我也在添加我的网络浏览器错误

jquery.dataTables.js:3929 Uncaught TypeError: Cannot set property 'data' of null
    at _fnBuildAjax (jquery.dataTables.js:3929)
    at _fnAjaxUpdate (jquery.dataTables.js:3946)
    at _fnDraw (jquery.dataTables.js:3409)
    at _fnReDraw (jquery.dataTables.js:3528)
    at _fnInitialise (jquery.dataTables.js:4710)
    at loadedInit (jquery.dataTables.js:1320)
    at HTMLTableElement.<anonymous> (jquery.dataTables.js:1332)
    at Function.each (jquery-2.1.4.js:374)
    at jQuery.fn.init.each (jquery-2.1.4.js:139)
    at jQuery.fn.init.DataTable [as dataTable] (jquery.dataTables.js:869)

【问题讨论】:

  • 由于您使用的是 asmx 页面中的 Web 服务,因此无法正常工作。
  • 所以我必须使用 ashx 处理程序?
  • 不,您只需要更改您的表格减免。给我几分钟

标签: jquery asp.net vb.net datatables


【解决方案1】:

这是我的做法。我使用帖子而不是使用 Web 服务获得了更大的成功。此外,因为您的 Web 服务正在序列化(我也是这样做的),所以 json 对象最终会被序列化两次。此外,数据表期望数据采用 {data: [your data] } 的形式,并且 Web 服务返回 {d:[your data serialized]} 您必须在客户端进行调整。这是我的做法。

    $(document).ready(function () {

        $('#example').DataTable({

            "processing": false,
            // since you are getting all the data at once set serverSide to
            // false, otherwise using the built in search and paging will trigger
            // more ajax calls to get the same data.
            "serverSide": false,
            "ajax": {

                // returning the data from the server as json data
                contentType: "application/json; charset=utf-8",
                // assuming your url is right....
                url: "../CONFIG/WebSerTblsSearch.asmx/SrcTblRegx",
                type: "Post",

             // You are not sending parameters to the server so next line commented out
                data: function (dtParms) { 
                    return  JSON.stringify({ SrchTxt: "your search string" }); 
                },
                dataFilter: function (res) {

                    // do what you need to the data before it loads to the table
                    // first deserialization
                    var parsed = JSON.parse(res);
                   // now you can access the data in d and deserialize that
                    var morp = JSON.parse(parsed.d);

                    // reserialize to what datatables expect.
                    return JSON.stringify( { data: morp });
                },
                error: function (x, y) {

                    console.log(x);

                }
            },
            columns:[
                {data:"Filenum"},
                {data: "FullName"},
                {data:"DOB"}]

        });

    });

【讨论】:

  • 谢谢,我收到了这个错误,,, DataTables 警告:table id=RegSrc2 - Requested unknown parameter '0' for row 0, column 0. 有关此错误的详细信息
  • 我通过添加列部分将数据类型从数组数组更改为对象数组
  • 你也参考了我的数据表声明,我把最终代码贴在下面,,,,,,非常感谢
  • binderi,对不起,我不能通过这个代码函数(dtParms)发送数据,,,,,,,我曾经通过定义var obj = {}发送数据;然后像 obj.searchtxt 一样向它添加参数,然后在 AJAX 调用数据部分中我使用 JSON.stringify(obj) ,,,, 我尝试了许多其他方法我一直收到糟糕的 web 服务调用,,, 请指教
  • 因为 DataTables 文档告诉您使用 success 可能会产生意想不到的副作用,因为他们使用它来用数据填充表。 dataFilter 在成功之前调用,因此您可以完成相同的事情而不会弄乱 DataTables 功能。
【解决方案2】:

我对上面的代码进行了更改,我使用的是数据表而不是数据集。

序列化数据表的代码

Public Function DataTableToJSONWithJavaScriptSerializer(table As DataTable) As String
    Dim jsSerializer As New JavaScriptSerializer()
    Dim parentRow As New List(Of Dictionary(Of String, Object))()
    Dim childRow As Dictionary(Of String, Object)
    For Each row As DataRow In table.Rows
        childRow = New Dictionary(Of String, Object)()
        For Each col As DataColumn In table.Columns
            childRow.Add(col.ColumnName, row(col))
        Next
        parentRow.Add(childRow)
    Next
    Return jsSerializer.Serialize(parentRow)
End Function

参考:http://www.c-sharpcorner.com/UploadFile/9bff34/3-ways-to-convert-datatable-to-json-string-in-Asp-Net-C-Sharp/

服务器端处理,webmethod(存储过程)

 <WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
       Public Function SrcTblReg(ByVal SrchTxt As String)
        
        Dim constr As String = ConfigurationManager.ConnectionStrings("ARTSQLConStrng").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("TblRegSearch", con)
            cmd.CommandType = CommandType.StoredProcedure
            If (String.IsNullOrEmpty(SrchTxt)) Then
                cmd.Parameters.Add("@Searchtxt", SqlDbType.NVarChar).Value = DBNull.Value
            Else
                cmd.Parameters.Add("@Searchtxt", SqlDbType.NVarChar).Value = SrchTxt.Trim()
            End If
                cmd.Connection = con
                Using sda As New SqlDataAdapter(cmd)
                    Dim dt As New DataTable()
                    sda.Fill(dt)
                    Dim sJSON = DataTableToJSONWithJavaScriptSerializer(dt)
                    Return sJSON
                End Using
                'Dim jsondata As String = JsonConvert.SerializeObject(ds)
                'Return jsondata
            End Using
        End Using
    End Function

最后是 Bindrid 提供的客户端。

$(document).ready(function () {

    $('#example').DataTable({

        "processing": false,
        // since you are getting all the data at once set serverSide to
        // false, otherwise using the built in search and paging will trigger
        // more ajax calls to get the same data.
        "serverSide": false,
        "ajax": {

            // returning the data from the server as json data
            contentType: "application/json; charset=utf-8",
            // assuming your url is right....
            url: "../CONFIG/WebSerTblsSearch.asmx/SrcTblRegx",
            type: "Post",

         // You are not sending parameters to the server so next line commented out
            data: function (dtParms) { 
                return  JSON.stringify({ SrchTxt: "your search string" }); 
            },
            dataFilter: function (res) {

                // do what you need to the data before it loads to the table
                // first deserialization
                var parsed = JSON.parse(res);
               // now you can access the data in d and deserialize that
                var morp = JSON.parse(parsed.d);

                // reserialize to what datatables expect.
                return JSON.stringify( { data: morp });
            },
            error: function (x, y) {

                console.log(x);

            }
        },
        columns:[
            {data:"Filenum"},
            {data: "FullName"},
            {data:"DOB"}]

    });

});

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    相关资源
    最近更新 更多