简体   繁体   English

如何使用AJAX与Web方法一起使用asp.net将JSON对象发送到jQuery DataTable?

[英]How can I use AJAX with web methods to send JSON objects to a jQuery DataTable using asp.net?

So I have the jQuery datatable using AJAX to call for the JSON in this format. 所以我有使用AJAX的jQuery数据表,以这种格式调用JSON。

 $(document).ready(function () {

            $('#test').DataTable({
                ajax:{
                    url:"players.json",
                    dataSrc:""
                  },
                columns: [
                    {data: "id"},
                    { data: "player" },
                    { data: "points" },
                    { data: "steals" },
                    { data: "blocks" },
                    { data: "assists" },
                    { data: "MPG" },
                    { data: "shot %" },
                    { data: "3 %" }
                ]


            });
        });

My aspx.cs file has a method to create the JSON file which works. 我的aspx.cs文件有一种创建有效的JSON文件的方法。

[System.Web.Services.WebMethod]
        public static void loadTable()
        {
            NBAPlayerRepository players = new NBAPlayerRepository();
            DataTable dt = players.GetAll();
            var json = dt.ToJson();
            System.IO.File.WriteAllText(@"C:\Users\wheres\Downloads\nbaStats\nbaStats\nbaStats\players.json", json);
        }

And the JSON looks like this: JSON看起来像这样:

[{"id" : "67926aa7-46b7-4418-96db-fc7e5216aac4","playername" : "Wilson Heres","points" : "34534","steals" : "34","blocks" : "34","assists" : "343","mpg" : "343","shootingpercentage" : "33.3429985046387","threepointpercentage" : "33.3429985046387"}
,{"id" : "6dc42e0b-8750-463d-a9ef-5a025a27154b","playername" : "Wilson Heres","points" : "34534","steals" : "34","blocks" : "34","assists" : "343","mpg" : "343","shootingpercentage" : "33.3429985046387","threepointpercentage" : "343.334014892578"}
,{"id" : "f727130c-5b94-4730-a653-cfb603c73b8a","playername" : "Wilson Heres","points" : "34534","steals" : "34","blocks" : "34","assists" : "343","mpg" : "343","shootingpercentage" : "33.3429985046387","threepointpercentage" : "343.334014892578"}
]

But now I am getting this error "jquery.dataTables.min.js:48 Uncaught TypeError: Cannot read property 'length' of undefined" 但是现在我收到此错误“ jquery.dataTables.min.js:48 Uncaught TypeError:无法读取未定义的属性'length'”

Edit: This all works now. 编辑:这一切现在都可以。 Just had to add dataSrc:"" 只需添加dataSrc:“”

Cleaned-up version of your DataTables initialization 数据表初始化的清理版本

 $(document).ready(function () {

        $('#test').DataTable({
            ajax: {
                url: "players.aspx/loadTable"
            },
            columns: [
               { data: "id" },
               { data: "player" },
               { data: "points" },
               { data: "steals" },
               { data: "blocks" },
               { data: "assists" },
               { data: "MPG" },
               { data: "Shot %" },
               { data: "3 %" },
            ]

    });
});

This may seem like a lot of stuff was removed from your code, so let me make some explanations/assumptions about what was changed. 这似乎已从您的代码中删除了很多内容,所以让我对更改内容进行一些解释/假设。

Assumptions 假设条件

  • First, an assumption: DataTables will always try to use a GET request, not a POST when first getting the data from the table, so make sure that your data processing code expects that. 首先,一个假设:第一次从表中获取数据时,DataTables将始终尝试使用GET请求,而不是POST ,因此请确保您的数据处理代码符合要求。
  • I also am assuming that you have no strong desire to have your Ajax separate from your initialization and that was just how you decided to do it as a first attempt. 我还假设您不希望将Ajax与初始化分开,而这正是您决定第一次尝试的方式。 If that is the case, let me know and I'll update the code to match that. 如果是这种情况,请告诉我,我将更新代码以使其匹配。

Explanation 说明

Your formatting is incorrect in some areas and against DataTables standard in others, so this version should do most of what you were trying to do in a much simpler form. 您的格式在某些方面不正确,而在另一些方面则违反了DataTables标准,因此此版本应以一种简单得多的形式完成您尝试执行的大部分操作。 A lot of your Ajax options are unnecessary because they are already the default (JSON for the data type, for example), which is why they have been removed. 您不需要使用许多Ajax选项,因为它们已经是默认选项(例如,数据类型为JSON),这就是为什么要删除它们的原因。

One nice thing about DataTables is that you can have the Ajax options in the initialization, which is what I have done here. 关于DataTables的一件好事是,您可以在初始化中使用Ajax选项,这就是我在这里所做的。 You do lose the success and failure callbacks but I think that for debugging purposes they aren't really necessary and having any extra code increases the amount of stuff to debug (I don't even use those callbacks in most of my final code). 您确实会丢失成功和失败回调,但是我认为对于调试目的而言,它们并不是真正必要的,拥有任何额外的代码会增加调试的工作量(我在大多数最终代码中甚至都不使用这些回调)。

Most of the other changes were mainly incorrect nomenclature (eg data instead of title in the column definitions. 其他大多数更改主要是不正确的命名法(例如, data而不是列定义中的title

Disclaimer 免责声明

While I would recommend these changes in general just to improve your code, I would make sure to take a look at the format of the JSON that is being sent to and from the server. 虽然我通常会建议这些更改只是为了改进您的代码,但我还是要确保了解一下发送到服务器或从服务器发送的JSON格式。 If you don't know how to do that I'd recommend downloading Fiddler to 'listen in' on the JSON data being sent. 如果您不知道该怎么做,建议您下载Fiddler以“收听”正在发送的JSON数据。

If your JSON is wrong, no amount of changes to the page are going to make the table appear. 如果您的JSON错误,则对页面的任何更改都不会使表格出现。

Finally, make sure you have no JS errors on the page. 最后,确保页面上没有JS错误。 Use your browser's developer console (F12) to check that. 使用浏览器的开发人员控制台(F12)进行检查。

If you do find any JS errors, post them in your question. 如果您发现任何JS错误,请将其发布在您的问题中。 I'd also recommend posting the JSON data being sent to the question as well so that we can ensure the format is correct. 我还建议您也发送要发送到问题的JSON数据,以便我们可以确保格式正确。

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

相关问题 如何使用asp.net生成并以字符串形式返回HTML文档(在Web上下文之外) - How can I use asp.net to generate and return an HTML document as a string (outside of a web context) 使用ASP.Net MVC,Ajax和Partial Views,如何更新我的URL? - Using ASP.Net MVC, Ajax, and Partial Views, how can I update my url? 如何基于asp.net角色使用jQuery隐藏或显示表行? - How can I use jQuery to hide or show table rows based on asp.net role? 我如何使用jquery数据表加载本地JSON变量 - how can i load the local JSON variable using jquery datatable 如何使用jQuery在Asp.Net中使用DatePicker控件 - How to use a DatePicker control in Asp.Net using jQuery 为什么我不能在ASP.NET MVC 2中使用强类型视图的Html辅助方法? - Why can't I use Html helper methods with strongly-typed views in ASP.NET MVC 2? 如何在ASP.NET中使用按钮标记? - How can I use the button tag with ASP.NET? 如何使用 ASP.NET MVC 通过 Ajax 将选中的行发送到服务器? - How to send checked rows to server via Ajax using ASP.NET MVC? 如何使用ajax显示从asp.net mvc5中的操作返回的json - how to use ajax to display json returned from action in asp.net mvc5 加载ASP.NET MVC Ajax表单时,如何阻止用户使用该页面? - How can I block the user from using the page while ASP.NET MVC Ajax unobtrusive form is loading?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM