jqGrid不显示JSON数据

时间:2011-02-16 15:13:22

标签: json jquery-ui jquery jqgrid

我希望将jqGrid用于我正在处理的当前Web项目。问题是,我似乎无法通过网格显示JSON数据。这是网格的初始化代码:

$.fn.loadjqgrid = function(httpposturl){
        $(this).jqGrid({
            url: httpposturl,
            datatype: "json",
            mtype: "GET",
            colNames: ["Video Title", "Description", "Date Taken", "Date Uploaded"],
            colModel: [
               {name:"videoTitle", index:"videoTitle", width:150},
               {name:"videoDescription", index:"videoDescription", width:200},
               {name:"dateTaken", index:"dateTaken", width:150, sortable:true},
               {name:"dateUploaded", index:"dateUploaded", width:150, sortable:true}
            ],
            pager: "#gridpager",
            rowNum: 10,
            viewrecords: true,
            caption: "Video Grid"
        });
    };

Java servlet返回的JSON:

[{"dateTaken":"Wed Feb 16 00:00:00 UTC 2011","videoDescription":"This is a test","videoTitle":"Test Video","dateUploaded":""}]

JSON的格式化方式或网格初始化方式是否有问题?谢谢你的帮助!

6 个答案:

答案 0 :(得分:7)

为了获得服务器端数据过滤的优势,分页和排序jqGrid可以更好地处理包含有关当前页面的其他信息的数据(请参阅here)。如果您无法更改生成JSON数据的服务器端,则可以添加loadonce:true参数,然后在本地完成数据的过滤,分页和排序。但首先jqGrid应该能够读取你的数据。

您可以使用我建议的jsonReader here(方式也记录为here):

jsonReader: {
    repeatitems: false,
    root: function (obj) { return obj; },
    page: function (obj) { return 1; },
    total: function (obj) { return 1; },
    records: function (obj) { return obj.length; }
}

使用jsonReader内部函数的方式非常灵活,你几乎可以通过jqGrid读取任何JSON数据。

修改后,您的网格将显示数据:请参阅here

留下一个小问题。 jqGrid需要为每个网格行都有唯一ID 。该ID将分配给每个<tr>元素。当前整数ids“1”,“2”,...将用作ID,因为在您的JSON数据中找不到ID。如果可以将一列网格解释为ID,则可以在jsonReader中包含相应的属性,例如id:"videoTitle"。如果您的数据确实没有ID,并且您计划将更多作为页面的一个网格,则可以收到ID冲突。在使用id作为两个网格的不同实现的函数的情况下可以解决问题。

答案 1 :(得分:4)

您可以验证返回的json是否有效:jsonlint

答案 2 :(得分:3)

底线,您返回的JSON数据结构不正确。

jqGrid的一个优点是使用自动与客户端jqGrid交互的服务器端库。如果由于某种原因您发现使用那些预先构建的服务器端库无法维护,那么您需要在jqGrid期望的结构中生成JSON。

从jqGrid JSON Data示例(http://www.trirand.com/blog/jqgrid/jqgrid.html)中,您的JSON应如下所示:

{"page":"1",
 "total":2,
 "records":"13",
 "rows":[{"id":"13","cell":["13","2007-10-06","Client 3","1000.00","0.00","1000.00",null]},
         {"id":"12","cell":["12","2007-10-06","Client 2","700.00","140.00","840.00",null]},
         {"id":"11","cell":["11","2007-10-06","Client 1","600.00","120.00","720.00",null]},
         {"id":"10","cell":["10","2007-10-06","Client 2","100.00","20.00","120.00",null]},
         {"id":"9","cell":["9","2007-10-06","Client 1","200.00","40.00","240.00",null]},
         {"id":"8","cell":["8","2007-10-06","Client 3","200.00","0.00","200.00",null]},
         {"id":"7","cell":["7","2007-10-05","Client 2","120.00","12.00","134.00",null]},
         {"id":"6","cell":["6","2007-10-05","Client 1","50.00","10.00","60.00",""]},
         {"id":"5","cell":["5","2007-10-05","Client 3","100.00","0.00","100.00","no tax at all"]},
         {"id":"4","cell":["4","2007-10-04","Client 3","150.00","0.00","150.00","no tax"]}],
 "userdata":{"amount":3220,"tax":342,"total":3564,"name":"Totals:"}}

对于您的数据集:

{"page":"1",
 "total:2,
 "records":"1",
 "rows":[{"id":"43", "cell":["Test Video","This is a test","Wed Feb 16 00:00:00 UTC 2011",""]}]}

答案 3 :(得分:2)

实际上,将JSON数据放入jqGrid非常简单,并让jqGrid处理分页和排序,而无需重新调用您的JSON服务。

关键是这一行:

loadonce: true,

现在,您的JSON服务无需担心页面总计记录正在发送的值。您只需加载一次JSON数据,然后让jqGrid完成剩下的工作。

因此,举例来说,这是我的一个JSON Web服务:

http://www.iNorthwind.com/Service1.svc/getOrdersForCustomer/BERGS

这是我想用它创建的jqGrid:

enter image description here

这是我的整个jqGrid脚本:

$("#tblOrders").jqGrid({
    url: 'http://www.iNorthwind.com/Service1.svc/getOrdersForCustomer/BERGS',
    contentType: "application/json",
    datatype: "json",
    jsonReader: {
        root: "GetOrdersForCustomerResult",
        id: "OrderID",
        repeatitems: false
    },
    mtype: "GET",
    colNames: ["ID", "Date", "ShipName", "ShipAddress", "ShipCity", "ShippedDate"],
    colModel: [
        { name: "OrderID", width: 80, align: "center" },
        { name: "OrderDate", width: 90, align: "center" },
        { name: "ShipName", width: 250 },
        { name: "ShipAddress", width: 250 },
        { name: "ShipCity", width: 95 },
        { name: "ShippedDate", width: 95 },
    ],
    pager: "#pager",
    height: 'auto',
    rowNum: 8,
    rowList: [8, 16, 24],
    loadonce: true,
    sortname: "OrderID",
    sortorder: "desc",
    viewrecords: true,
    gridview: true,
    autoencode: true,
    caption: "Northwind orders"
});

就是这样。

我博客的更多详情:

www.MikesKnowledgeBase.com

答案 4 :(得分:2)

如果以JSON格式发送数据,则无需使用jsonReader

例如: 我的模型(jqGridModel.cs)看起来像这样 -

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace jqGrid.Models
{

public class jqGridModel

{

    public string CompanyName { get; set; }
    public string RooftopName { get; set; }
    public string UpdatedBy { get; set; }
    public string UpdatedDate { get; set; }
}

}

现在,您需要做的就是通过控制器

以Json格式发送数据

----------- jqGridController.cs ----------------

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using jqGrid.Models;

namespace jqGrid.Controllers
{
public class jqGridController : Controller
{
    //
    // GET: /jqGrid/

    public ActionResult jqGridView ()
    {
        return View();
    }

    public JsonResult jqGridViewjson()
    {

        List<jqGridModel> company = new List<jqGridModel>();
        company.Add(new jqGridModel(){
             CompanyName="Ms", 
             RooftopName ="MS",
             UpdatedBy ="Vivek",
             UpdatedDate=DateTime.Today.ToString("dd/MM/yyyy")
        });
        Console.Write(company);
       company.Add(new jqGridModel()
        {
            CompanyName = "Ms1",
            RooftopName = "Ms1",
            UpdatedBy = "Pankaj",
            UpdatedDate = DateTime.Today.ToString("dd/MM/yyyy")
        });

        var result = Json(company, JsonRequestBehavior.AllowGet);
        return result;

    }

  }
 }

最后是脚本文件

---------------- jqGridScript.js ---------------

 $(document).ready(function () {

 jQuery("#grid").jqGrid({

    url: '/jqGrid/jqGridViewjson',
    contentType: "application/json",
    datatype: "json",   
    colNames: ['Company Name', 'Rooftop Name', 'Updated By', 'UpdatedDate'],
    colModel: [
        { name: 'CompanyName', index: 'CompanyName', width: 150 },
        { name: 'RooftopName', index: 'RooftopName', width: 150 },
        { name: 'UpdatedBy', index: 'UpdatedBy', width: 150 },
        { name: 'UpdatedDate', index: 'UpdatedDate', width: 150}            
    ],
    rowNum: 10,
    mtype: "GET",        
    rowList: [10, 20, 30],
    pager: '#pager',
    loadonce: true,
    viewrecords: true,
    sortorder: "desc",
    autoencode: true,
    caption: "Company approval"       
});
jQuery("#grid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
});

--------------- jqGridView.cshtml ----------------

<!DOCTYPE html>
<html>
<head>
<title>jqGrid</title>
<link href="~/StyleSheet/bootstrap.css" rel="stylesheet" />
<link href="~/StyleSheet/bootstrap-theme.min.css" rel="stylesheet" />
<link href="~/StyleSheet/jquery-ui.css" rel="stylesheet" />
<link href="~/StyleSheet/ui.jqgrid-bootstarp.css" rel="stylesheet" />
<link href="~/StyleSheet/ui.jqgrid.css" rel="stylesheet" />

</head>
<body>

 <div>
   <table id="grid"></table>
   <div id="pager"></div>
</div>

 <script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/grid.locale-en.js"></script>
<script src="~/Scripts/jquery.jqGrid.src.js"></script>
<script src="~/Scripts/jqGridScript.js"></script>  

</body>
</html>

答案 5 :(得分:1)

也许这仅仅是引用或双引号的问题。这很敏感。在那里举例:

jQuery("#list5").jqGrid({ url:'server.php?q=2', 
datatype: "json", 
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'], colModel:[ {name:'id',index:'id', width:55}, {name:'invdate',index:'invdate', width:90}, {name:'name',index:'name', width:100}, {name:'amount',index:'amount', width:80, align:"right"}, {name:'tax',index:'tax', width:80, align:"right"}, {name:'total',index:'total', width:80,align:"right"}, {name:'note',index:'note', width:150, sortable:false} ], rowNum:10, ......