草庐IT

javascript - 使用 REST API 的可编辑 jQuery 网格推荐

coder 2024-07-24 原文

首先,我已经阅读了问题“jQuery Grid Recommendations”,但它没有回答我的问题。

我有一个小REST API with MongoDB Backend只是:

获取所有装备:

GET /equipements HTTP/1.1
{{_id:key1, name:Test Document 1, plateforme:prod}, {_id:key2, name:Test Document 2, plateforme:prod}, ...}

使用 key 获取设备:key1

GET /equipements/key1 HTTP/1.1
{"_id": "key1", "name": "Test Document 1", "plateforme": "prod"}

添加新设备

PUT /equipements HTTP/1.1  {"_id": "key8", "name": "Test Document 3", "plateforme": "prod"}
HTTP/1.0 200 OK

现在,我需要找到一种允许 lambda 用户添加/查看/删除 设备的简单方法。所以我认为带有类似 UI 的 jQuery 的 Web 界面是最好的。我 triedSencha Rest Proxy但我不懂 javascript,也未能适应该示例。

如何修复我的 REST 后端的 javascript?

和/或

你能推荐一个比 Sencha Rest Proxy 更简单的替代品吗?(它适用于我的 REST 后端)

答案:jqGrid

和/或

您会向我推荐什么 jQuery Grid?(与我的 REST 后端一起使用)

答案:jqGrid

最后一个问题:为什么我的单元格不能通过双击进行编辑?

附录

服务器端(编辑:添加方法 POST)

#!/usr/bin/python
import json
import bottle
from bottle import static_file, route, run, request, abort, response
import simplejson
import pymongo
from pymongo import Connection
import datetime



class MongoEncoder(simplejson.JSONEncoder):
    def default(self, obj):
                # convert all iterables to lists
        if hasattr(obj, '__iter__'):
            return list(obj)
        # convert cursors to lists
        elif isinstance(obj, pymongo.cursor.Cursor):
            return list(obj)
        # convert ObjectId to string
        elif isinstance(obj, pymongo.objectid.ObjectId):
            return unicode(obj)
        # dereference DBRef
        elif isinstance(obj, pymongo.dbref.DBRef):
            return db.dereference(obj)
        # convert dates to strings
        elif isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date) or isinstance(obj, datetime.time):
            return unicode(obj)
        return simplejson.JSONEncoder.default(self, obj)



connection = Connection('localhost', 27017)
db = connection.mydatabase

@route('/static/<filename:path>')
def send_static(filename):
    return static_file(filename, root='/home/igs/restlite/static')

@route('/')
def send_static():
    return static_file('index.html',root='/home/igs/restlite/static/')

@route('/equipements', method='PUT')
def put_equipement():
    data = request.body.readline()
    if not data:
        abort(400, 'No data received')
    entity = json.loads(data)
    if not entity.has_key('_id'):
        abort(400,'No _id specified')
    try:
        db['equipements'].save(entity)
    except ValidationError as ve:
        abort(400, str(ve))

@route('/equipements', method='POST')
def post_equipement():
    data = request.forms

    if not data:
        abort(400, 'No data received')
    entity = {}
    for k,v  in data.items():
        entity[k]=v

    if not entity.has_key('_id'):
        abort(400,'No _id specified')
    try:
        db['equipements'].save(entity)
    except ValidationError as ve:
        abort(400, str(ve))


@route('/equipements/:id', methodd='GET')
def get_equipement(id):
    entity = db['equipements'].find_one({'_id':id})
    if not entity:
        abort(404, 'No equipement with id %s' % id)
    return entity

@route('/equipements', methodd='GET')
def get_equipements():
    entity = db['equipements'].find({})
    if not entity:
        abort(404, 'No equipement')
    response.content_type = 'application/json'
    entries = [entry for entry in entity]
    return MongoEncoder().encode(entries)

run(host='0.0.0.0', port=80)

编辑:JQGrid:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Rest Proxy Example</title>
    <link rel="stylesheet" type="text/css" href="/static/css/ui.jqgrid.css" />
    <link rel="stylesheet" type="text/css" href="/static/css/jquery-ui-1.8.20.custom.css" />

    <script type="text/javascript" src="/static/js/jquery.js"></script>
    <script type="text/javascript" src="/static/js/jquery.jqGrid.min.js"></script>
    <script type="text/javascript" src="/static/js/grid.locale-fr.js"></script>
    <script type="text/javascript">
        jQuery(document).ready(function(){
            var lastsel;

jQuery("#list2").jqGrid({
    url:'equipements',
    datatype: "json",
    colNames:['Id','Name', 'Plateforme'],
    colModel:[
        {name:'_id',index:'_id', width:50, editable:true},
        {name:'name',index:'_id', width:300, editable:true},
        {name:'plateforme',index:'total', width:200,align:"right", editable:true},
    ],
    rowNum:30,
    rowList:[10,20,30],
    pager:'pager2',
    sortname: '_id',
    viewrecords: true,
    width: 600,
    height: "100%",
    sortorder: "desc",
    onSelectRow: function(_id){
        if(_id && _id!==lastsel){
            jQuery('#liste2').jqGrid('restoreRow',lastsel);
            jQuery('#liste2').jqGrid('editRow',_id,true);
            lastsel=_id;
        }
    },
    jsonReader: {
        repeatitems: false,
        id: "_id",
        root: function (obj) { return obj; },
        records: function (obj) { return obj.length; },
        page: function (obj) { return 1; },
        total: function (obj) { return 1; }
    },
    editurl:'equipements',
    caption:"Equipements"
});
jQuery("#list2").jqGrid('navGrid','#pager2',{edit:true,add:true,del:true});
});
    </script>
</head>
<body>
    <table id="list2"></table>
    <div id="pager2"></div>
    <br />

</body>
</html>

最佳答案

您可以使用 jqGrid 与您的 RESTfull 服务进行通信。 jqGrid 支持树编辑模式:单元格编辑、内联编辑和表单编辑。此外,内联编辑可以用不同的方式初始化。例如可以调用 editRow onSelectRowondblClickRow 回调中的方法或使用 navGridnavigator 中添加“删除”按钮工具栏和 inlineNav添加“添加”和“编辑”按钮。另一种方法是使用 formatter: "actions"在网格的一列中包含“编辑”按钮。您可以在the official jqGrid demo中找到所有方法.您可以在 the answer 中找到更多技术实现细节.

我个人认为了解在网络前端中使用 RESTfull 服务的另一个重要方面很重要。问题是标准的 RESTfull API 没有任何用于数据排序、分页和过滤的标准接口(interface)。我试着解释下面的问题。在那之后,我希望我的建议是使用具有附加参数并提供排序、分页和过滤功能的附加方法来扩展当前标准 RESTfull API

如果你有大数据集,这个问题就很容易理解。例如一次在网格中显示 10000 行数据是没有意义的。如果不对数据进行滚动分页,用户将无法在屏幕上看到数据。此外,由于同样的原因,对数据进行排序甚至过滤也是有意义的。所以一开始只显示一页数据,给用户一些数据分页的接口(interface),会实用很多。中标pager jqGrid 看起来像

用户可以转到“下一页”、“最后一页”、“上一页”或“第一页”或选择页面大小:

此外,用户可以通过直接输入新页面并按 Enter 来指定所需页面:

以相同的方式,用户可以单击任何列的标题以按列对网格数据进行排序:

另一个非常重要的用户界面元素(从用户的 Angular 来看很重要)可能是一些过滤界面,如 here例如或搜索类似 here 的界面.

我给你举了 jqGrid 的例子,但我发现这个问题很常见。 我想强调的是,RESTfull 服务没有为您提供数据排序、分页和过滤的标准接口(interface)

在使用 jqGrid 的情况下,默认情况下 RESTfull url 将获得附加参数。它是:pagerows,指定将从服务请求的页码和页面大小,sidxsord 指定排序列和排序方向的参数以及允许支持过滤的 _searchfilters (最后一个在 the format 中)。如果需要,可以使用 prmNames 重命名参数jqGrid 的选项。

我推荐你阅读the answer关于 URL 编码的问题。我认为 _search=false&rows=20&page=1&sidx=&sord=asc 部分不属于资源,因此最好将信息作为参数而不是部分发送网址。

我在回答中主要想表达的是,使用纯经典的RESTfull API 不足以实现良好的用户界面。您将不得不使用用于分页、排序和过滤的额外参数来扩展界面,否则您将无法创建高性能且用户友好的 Web GUI。

关于javascript - 使用 REST API 的可编辑 jQuery 网格推荐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10732684/

有关javascript - 使用 REST API 的可编辑 jQuery 网格推荐的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  10. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

随机推荐