jqGrid 不填充数据 [英] jqGrid does not populate with data

查看:30
本文介绍了jqGrid 不填充数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自 Web 服务的数据填充 jqGrid.我已经彻底查看了 jqGrid 代码和文档.我需要另一双眼睛来查看下面的代码并告诉我是否遗漏了什么.

I am trying to populate a jqGrid with data from a web service. I have looked at the jqGrid code and documentation thoroughly. I need another set of eyes to look at the code below and tell me if I'm missing something.

正如您将在代码中看到的,我将网格设置为在页面加载或刷新期间加载.网格加载后,我进行 Ajax 调用以获取 JSON 数据(再次)并显示在网格下方的 div 中.

As you'll see in the code, I have the grid set up to load when the page loads or during a refresh. After the grid loads, I make an Ajax call to get the JSON data (again) and display in a div below the grid.

我看到了大部分预期行为.页面加载后,网格显示加载指示器,然后启动 Ajax 调用,并在网格下方显示 JSON 数据.问题是网格完全是空的.列标题是正确的,但网格主体中没有显示任何数据.

I see most of the expected behavior. After the page loads, the grid displays the loading indicator, then the Ajax call is initiated and the JSON data is shown below the grid. The problem is that the grid is completely empty. The column headers are correct, but no data appears in the body of the grid.

代码如下:

$(document).ready(function () {
    $('#resultDiv').html('');
    $('#waitIndicator').hide();
    $("#list").jqGrid({
        datatype: 'json',
        url: 'WeatherDataService.svc/GetWeatherData',
        jsonReader: {
            root: "Rows",
            page: "Page",
            total: "Total",
            records: "Records",
            repeatitems: false,
            userdata: "UserData",
            id: "StationId"
        },
        loadui: "block",
        mtype: 'GET',
        rowNum: 10,
        rowList: [10, 20, 30],
        viewrecords: true,
        colNames: ['Station ID', 'Station Name', 'Timestamp', 'Max Temp',
                   'Min Temp', 'Precipitation', 'Snowfall', 'SnowDepth'],
        colModel: [
            { name: 'StationId', index: 'StationId' },
            { name: 'StationName', index: 'StationName' },
            { name: 'Timestamp', index: 'Timestamp', align: 'right' },
            { name: 'MaxTemperature', index:'MaxTemperature',align:'right'},
            { name: 'MinTemperature', index:'MinTemperature',align:'right'},
            { name: 'Precipitation', index: 'Precipitation', align:'right'},
            { name: 'Snowfall', index: 'Snowfall', align: 'right' },
            { name: 'SnowDepth', index: 'SnowDepth', align: 'right' },
        ],
        pager: '#pager',
        sortname: 'StationId',
        sortorder: 'asc',
        caption: 'Weather Records',
        loadComplete: function () {
            // if the page index is not set (e.g. page index = 0),
            // force the page index to first page
            var pageIndex = $('#list').jqGrid('getGridParam', 'page');
            if (pageIndex == 0) pageIndex = 1;

            $('#waitIndicator').show();
            $.ajax({
                url: 'WeatherDataService.svc/GetWeatherData',
                type: "GET",
                data: ({ page: pageIndex, rows: 10,
                         sidx: 'StationId', sord: 'asc' }),
                dataType: "json",
                success: function (response) {
                    $('#resultDiv').html(response);
                    $('#waitIndicator').hide();
                },
                error: function (xmlHttpRequest, textStatus, errorThrown) {
                    $('#resultDiv').html('textStatus: ' + textStatus + 
                                         ', errorThrown: ' + errorThrown);
                }
            });
        }
    });
}); 

这是来自 Web 服务的 JSON 数据:

Here is the JSON data from the web service:

{
    "Total": 14975,
    "Page": 1,
    "Records": 149746,
    "Rows": [
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(725871600000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(725958000000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(726044400000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(726130800000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(726217200000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(726303600000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(726390000000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(726476400000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(726562800000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        },
        {
            "StationId": 50130,
            "StationName": "ALAMOSA WSO AP",
            "Timestamp": "/Date(726649200000)/",
            "MaxTemperature": null,
            "MinTemperature": null,
            "Precipitation": null,
            "Snowfall": null,
            "SnowDepth": null
        }
    ],
    "UserData": null
}

对于大多数列,空值将导致空单元格.但我希望至少能看到 StationIDs 和 StationNames.感谢观看.

For most of the columns the null values will result is empty cells. But I expect to see at least the StationIDs and StationNames. Thanks for taking a look.

推荐答案

首先,如果服务器将您发布的数据发回,jqGrid 会显示结果(参见 http://www.ok-soft-gmbh.com/jqGrid/jsonfromsvc​​.htm).因为 jqGrid 的效果不是很好,因为您使用 StationId 作为 id,但 JSON 数据中的所有行都具有 相同 值 50130 作为 id.因此,例如,如果您选择一行,则会选择所有行.

First of all if the server send back the data which you posted, the jqGrid will do displayed the results (see http://www.ok-soft-gmbh.com/jqGrid/jsonfromsvc.htm). Of cause jqGrid will works not really good, because you use StationId as the id, but all rows in your JSON data has the same value 50130 as the id. So, for example, if you select one row all rows will be selected.

DateTime 不是标准的 JSON 类型,jqGrid 目前不支持它(参见 这个答案此功能请求).要解决此问题,您必须至少在数据和 jqGrid.

The DateTime is not a standard JSON type and it is not supported currently by jqGrid (see this answer and this feature request). To fix the problem you have to make at least some small changes in both data and the jqGrid.

当前的JSON数据有很多空值的数据.要减少从服务器发送的空数据的大小,请考虑使用 EmitDefaultValue 属性.

The current JSON data has a lot of data with null value. To reduce the size of empty data send from the server consider to use EmitDefaultValue attribute.

而且我觉得奇怪,你没有使用像

Moreover I find strange, that you not use parameters like

ajaxGridOptions: { contentType: "application/json" },
serializeRowData: function (data) {return JSON.stringify(data);}

(参见另一个旧答案).可能您的 WFC 当前没有接收任何输入参数,例如 int page、int rows、string sidx、string sord 等).如果您至少发布了您调用的服务器方法的原型.

(see another old answer). Probably your WFC don't receive currently any input parameters like int page, int rows, string sidx, string sord and so on). If you post at least prototype of your server method which you call.

更新:在我创建一个小型 WCF 应用程序和一个调用 WCF 服务的 HTML 页面之前我是如何承诺的.

UPDATED: How I promised before I created a small WCF application and a HTML page which call the WCF service.

您当前的数据没有 ID.字段 StationId 不是键,因为它在不同的数据行中是相同的.如果您在数据中包含 id,您可以在列定义中包含选项 key:true 和 jqGrid 将使用数据作为 id.因为该示例仅用于显示数据而不进行数据编辑,所以我在从服务器发送的数据中包含了 no id.在 jqGrid 使用从 1 开始的整数计数器作为行 ID 的情况下.如果您决定在网格中包含编辑功能,则必须将其作为 id 包含在数据中.

Your current data has no id. The field StationId along is not a key because it is the same in different data rows. If you include id in your data you can include in the column definition the option key:true and jqGrid will use the data as the id. Because the example will be used only to display the data without data editing I included no id in the data send from the server. In the case jqGrid use integer counter starting with 1 as the row ids. If you decide to include editing features in the grid you will have to include as id in the data.

现在我们进入代码.因为您写道您使用 Visual Studio 2010 并且没有回答有关 .NET 版本的任何问题,所以我在 .NET 4.0 中创建了一个应用程序.web.config:

Now we go to the code. Because You wrote that you use Visual Studio 2010 and answer nothing about the version of .NET I created an application in .NET 4.0. The web.config:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>

    <system.serviceModel>
        <standardEndpoints>
            <webHttpEndpoint>
                <standardEndpoint helpEnabled="true"
                                  automaticFormatSelectionEnabled="true"/>
            </webHttpEndpoint>
        </standardEndpoints>
        <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
</configuration>

文件WeatherDataService.svc:

<%@ ServiceHost Factory="System.ServiceModel.Activation.WebServiceHostFactory"
                Service="WfcToJqGrid.WeatherDataService" %>

文件IWeatherDataService.cs:

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace WfcToJqGrid {
    [ServiceContract]
    public interface IWeatherDataService {
        [OperationContract,
         WebGet (RequestFormat = WebMessageFormat.Json,
                 ResponseFormat = WebMessageFormat.Json,
                 UriTemplate = "GetWeatherData?page={page}&rows={rows}" +
                               "&sidx={sortIndex}&sord={sortDirection}")]
        WeatherDataForJqGrid GetDataForjqGrid (int page, int rows,
                                               string sortIndex,
                                               SortDirection sortDirection);
    }

    [DataContract]
    public enum SortDirection {
        [EnumMember (Value = "asc")]
        Asc,
        [EnumMember (Value = "desc")]
        Desc
    }

    // jsonReader: { repeatitems: false }
    [DataContract]
    public class WeatherDataForJqGrid {
        [DataMember (Order=0, Name = "total")]
        public int Total { get; set; }          // total number of pages
        [DataMember (Order = 1, Name = "page")]
        public int Page { get; set; }           // current zero based page number
        [DataMember (Order = 2, Name = "records")]
        public int Records { get; set; }        // total number of records
        [DataMember (Order = 3, Name = "rows")]
        public IEnumerable<WeatherData> Rows { get; set; }
    }

    [DataContract]
    public class WeatherData {
        [DataMember (Order=0)]
        public int StationId { get; set; }
        [DataMember (Order = 1)]
        public string StationName { get; set; }
        [DataMember (Order = 2)]
        public DateTime Timestamp { get; set; }
        [DataMember (Order = 3, EmitDefaultValue = false)]
        public string MaxTemperature { get; set; }
        [DataMember (Order = 4, EmitDefaultValue = false)]
        public string MinTemperature { get; set; }
        [DataMember (Order = 5, EmitDefaultValue = false)]
        public string Precipitation { get; set; }
        [DataMember (Order = 6, EmitDefaultValue = false)]
        public string Snowfall { get; set; }
        [DataMember (Order = 7, EmitDefaultValue = false)]
        public string SnowDepth { get; set; }
    }
}

文件WeatherDataService.svc.sc:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Web;
using System.Net;

namespace WfcToJqGrid {
    public class WeatherDataService : IWeatherDataService {
        // we use very simple database model to simulate a real data
        private static IQueryable<WeatherData> _repository = new List<WeatherData>{
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,1,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,2,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,3,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,4,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,5,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,6,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,7,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,8,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                              Timestamp = new DateTime(1993,1,9,8,0,0)},
            new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP",
                             Timestamp = new DateTime(1993,1,10,8,0,0)}
        }.AsQueryable ();

        public WeatherDataForJqGrid GetDataForjqGrid (int page, int rows,
                                                      string sortIndex,
                                                      SortDirection sortDirection){
            int totalRecords = _repository.Count();

            // sorting of data
            IQueryable<WeatherData> orderdData = _repository;
            System.Reflection.PropertyInfo propertyInfo =
                typeof(WeatherData).GetProperty (sortIndex);
            if (propertyInfo != null) {
                orderdData = sortDirection == SortDirection.Desc ?
                    (from x in _repository
                     orderby propertyInfo.GetValue (x, null) descending
                     select x) :
                    (from x in _repository
                     orderby propertyInfo.GetValue (x, null)
                     select x);
            }

            // paging of the results
            IEnumerable<WeatherData> pagedData = orderdData
                .Skip ((page > 0? page - 1: 0) * rows)
                .Take (rows);

            // force revalidate data on the server on every request
            if (WebOperationContext.Current != null)
                WebOperationContext.Current.OutgoingResponse.Headers.Set (
                    HttpResponseHeader.CacheControl, "max-age=0");

            return new WeatherDataForJqGrid {
                Page = page,
                Records = totalRecords,
                Total = (totalRecords + rows - 1) / rows,
                Rows = pagedData
            };
        }
    }
}

(阅读有关缓存的更多信息 "jqGrid 数据存储在浏览器缓存中?")和 default.htm:

(read more about caching "jqGrid data stored in browser cache?") and default.htm:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Demonstration how use jqGrid to call WFC service</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/redmond/jquery-ui.css" />
    <link rel="stylesheet" type="text/css" href="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-3.8/css/ui.jqgrid.css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-3.8/js/i18n/grid.locale-en.js"></script>
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-3.8/js/jquery.jqGrid.min.js"></script>
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/json2.js"></script>
    <script type="text/javascript">
    //<![CDATA[
        jQuery(document).ready(function () {
            $("#list").jqGrid({
                datatype: 'json',
                url: 'WeatherDataService.svc/GetWeatherData',
                jsonReader: { repeatitems: false },
                loadui: "block",
                mtype: 'GET',
                rowNum: 5,
                rowList: [5, 10, 20, 30],
                viewrecords: true,
                colNames: ['Station ID', 'Station Name', 'Timestamp', 'Max Temp',
                           'Min Temp', 'Precipitation', 'Snowfall', 'SnowDepth'],
                colModel: [
                    { name: 'StationId', index: 'StationId', width: 100 },
                    { name: 'StationName', index: 'StationName', width: 150 },
                    { name: 'Timestamp', index: 'Timestamp', align: 'right', width: 250,
                        formatter: function (cellvalue, options, rowObject) {
                            // possible characters like "+0100" at the end of string will be ignored
                            return new Date(parseInt(cellvalue.substr(6, cellvalue.length - 8), 10));
                        }
                    },
                    { name: 'MaxTemperature', index: 'MaxTemperature', align: 'right', width: 100 },
                    { name: 'MinTemperature', index: 'MinTemperature', align: 'right', width: 100 },
                    { name: 'Precipitation', index: 'Precipitation', align: 'right', width: 100 },
                    { name: 'Snowfall', index: 'Snowfall', align: 'right', width: 100 },
                    { name: 'SnowDepth', index: 'SnowDepth', align: 'right', width: 100 },
                ],
                pager: '#pager',
                sortname: 'Timestamp',
                sortorder: 'asc',
                height: "100%",
                width: "100%",
                prmNames: { nd: null, search: null }, // we switch of data caching on the server
                                                      // and not use _search parameter
                caption: 'Weather Records'
            });
        });
    //]]>
    </script>
</head>

<body>

<table id="list"><tr><td/></tr></table>
<div id="pager"></div>

</body>
</html>

您可以在此处下载完整代码.

You can download the full code here.

这篇关于jqGrid 不填充数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆