使用 json 数据自动完成的 jqGrid 工具栏搜索 [英] jqGrid toolbar search with autocomplete using json data

查看:21
本文介绍了使用 json 数据自动完成的 jqGrid 工具栏搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了 Oleg (http://www.ok-soft-gmbh.com/jqGrid/FillToolbarSearchFilter.htm) 的非常好的演示,它显示了使用本地数据自动完成的 jqGrid 工具栏搜索",但很难获得这可以通过 ajax 为 json 工作.自动完成功能不起作用是否有充分的理由 - 即使我在加载后强制网格位于本地?

$(document).ready(function() {var mygrid = $("#mylist"),mygetUniqueNames = 函数(列名){var texts = mygrid.jqGrid('getCol',columnName), uniqueTexts = [],textsLength = texts.length, text, textsMap = {}, i;对于 (i=0;i

解决方案

jQuery UI Autocomplete 的远程 source 参数的使用很难举例.主要问题是您的问题是关于 jqGrid 的,它是 纯 JavaScript 解决方案.如果我们讨论该解决方案的服务器部分,我们将有太多选择.许多用户使用不同的语言:Java、C#、VB、PHP 等.例如,我个人更喜欢 C#.然后我们必须选择我们使用的技术:ASP.NET MVC、WCF、ASPX Web 服务等等.例如,我会选择 WCF.然后我们应该定义数据库访问技术,例如Entity Framework、LINQ to SQL、SqlDataReaderSqlDataAdapter等等.让我们选择 Entity Framework 并为您提供相应的代码示例,但如果您使用 PHP 和 MySQL 等,它不会真正帮助您.

所以我只是描述了jQuery UI Autocomplete 没有任何代码的远程source参数应该有服务器的接口.

您应该在我的示例中将 source 参数替换为您的服务器 url,如下所示:

dataInit: function(elem) {$(elem).autocomplete({来源:'yourSearchUrl.php',最小长度:2});}

如果用户输入两个字符(值可以通过minLength选项改变),例如'ab',那么自动完成将使用参数term=ab<发出HTTP GET请求/代码>:

yourSearchUrl.php?term=ab

您的服务器应以与本地源相同的格式回答 JSON 数据.我在前面的示例中使用了字符串数组格式.另一种支持的格式是具有标签/值/两个属性的对象数组,例如

<代码>[{"id": "Dromas ardeola","label": "蟹鸻",价值":蟹鸻"},{"id": "Larus sabini","label": "Sabine`s Gull","value": "萨宾海鸥"},{"id": "Vanellus gregarius","label": "善于交际的田凫",价值":善于交际的田凫"},{"id": "Oenanthe 伊莎贝丽娜",标签":伊莎贝琳小麦",价值":伊莎贝琳小麦"}]

阅读文档了解更多信息.

如果您需要实现更复杂的场景并向服务器发送一些额外的数据或以任何方式转换服务器响应,您可以使用自定义源回调函数.在这种情况下,您应该使用 source: function(request, response) {/*your implementation*/},其中 request 将是具有 term<的对象/code> 属性(request.term).在您的实现中,您应该手动向服务器发出 ajax 请求.response 将是回调函数,您应该在自定义 ajax 请求完成后调用 (在 success 事件处理程序内部).response 函数应使用参数调用,该参数应为与 mygetUniqueNames 返回格式相同的数组.我建议您检查 jQuery Autocomplete demo 的源代码.p>

要从表格的一列中提供唯一数据,您应该只使用大多数数据库都支持的 SELECT DISTINCT SQL 语句.

希望我的描述对你有所帮助.

更新:如果您有本地资源,则可以在 我的旧答案,您已经使用了.你只需要调用filterToolbar 源数组填充后.因为您从服务器加载数据,您应该移动 filterToolbarloadComplete 内.您使用 loadonce:true jqGrid 选项将 datatype'json' 切换到 'local' 在第一个之后数据加载.所以你可以在 loadComplete 事件处理程序中包含您的网格代码如下:

var grid = $('#list');网格({url:'autocompleteTest.php',数据类型:'json',加载一次:真,//... 其他参数加载完成:函数(数据){if (grid.getGridParam('datatype') === 'json') {//构建自动完成的 set 'source' 参数grid.jqGrid('setColProp', '名称', {搜索选项:{sopt:['bw'],数据初始化:函数(元素){$(elem).autocomplete({来源:mygetUniqueNames('name'),延迟:0,最小长度:0});}}});mygrid.jqGrid('filterToolbar',{stringResult:true,searchOnEnter:true,默认搜索:bw"});}}});

如果您需要从服务器重新加载数据(将 datatype 更改为 'json' 并调用 grid.trigger('reloadGrid')) 您将不得不更改上面的代码,以便您首先使用 $('#gs_name').autocomplete('destroy') 销毁 autocomplete 小部件和然后使用与 dataInit 内部相同的代码再次创建它.

I found the very nice demo by Oleg (http://www.ok-soft-gmbh.com/jqGrid/FillToolbarSearchFilter.htm) which shows a "jqGrid toolbar search with autocomplete using local data" but have trouble to get this to work for json via ajax. Is there a good reason why the autocomplete feature won't work - even if I force the grid to be local after loading?

$(document).ready(function() {

    var mygrid = $("#mylist"),
    mygetUniqueNames = function(columnName) {
        var texts = mygrid.jqGrid('getCol',columnName), uniqueTexts = [],
            textsLength = texts.length, text, textsMap = {}, i;
        for (i=0;i<textsLength;i++) {
            text = texts[i];
            if (text !== undefined && textsMap[text] === undefined) {
                // to test whether the texts is unique we place it in the map.
                textsMap[text] = true;
                uniqueTexts.push(text);
            }
        }
        return uniqueTexts;
    };





    mygrid.jqGrid({
            url:'autocompleteTest.php',
            datatype: "json",
            colNames:['name', 'City','stateCd'],
            colModel:[                      
                    {name:'name',index:'name',width:225, search: true},
                    {name:'City',index:'City',width:125},
                    {name:'stateCd',index:'stateCd',width:75},
                  ],

         rowNum: 100,
        loadonce : true,
         sortname: 'name',
        sortorder: 'desc',
         sortable: true,
        viewrecords: true,
        rownumbers: true,
        sortorder: "desc",
        ignoreCase: true,
        pager: '#mypager',
        height: "auto",
        caption: "How to use filterToolbar better with data from server"
    }).jqGrid('navGrid','#mypager',
              {edit:false, add:false, del:false, search:false, refresh:false});

    mygrid.jqGrid('setColProp', 'name',
            {
                searchoptions: {
                    sopt:['bw'],
                    dataInit: function(elem) {
                        $(elem).autocomplete({
                            source:mygetUniqueNames('name'),
                            delay:0,
                            minLength:0
                        });
                    }
                }
            });

    mygrid.jqGrid('filterToolbar',
            {stringResult:true, searchOnEnter:true, defaultSearch:"bw"});

    });

解决方案

It is difficult to provide an example in case of the usage of remote source parameter of jQuery UI Autocomplete. The main problem is that your question is about jqGrid which is pure JavaScript solution. If we would discuss the server part of tha solution we would have too options. Many users uses different languages: Java, C#, VB, PHP and so on. For example I personally prefer C#. Then we would have to choose the technology which we use: ASP.NET MVC, WCF, ASPX web service and so on. For example I would choose WCF. Then we should define the database access technology, for example, Entity Framework, LINQ to SQL, SqlDataReader, SqlDataAdapter and so on. Let us I would choose Entity Framework and would provide you the corresponding code example, but it would help you not really if you use for example PHP and MySQL.

So I just describe which interface should have the server for the remote source parameter of jQuery UI Autocomplete without any code.

You should replace in my example the source parameter to your server url like following:

dataInit: function(elem) {
    $(elem).autocomplete({
        source:'yourSearchUrl.php',
        minLength:2
    });
}

If the user types two characters (the value can be changed by minLength option), for example 'ab' then the autocomplete will make HTTP GET request with the parameter term=ab:

yourSearchUrl.php?term=ab

your server should answer with the JSON data in the same format as for the local source. I used the string array format in my previous example. Another supported format is array of objects with label/value/both properties like

[
    {
        "id": "Dromas ardeola",
        "label": "Crab-Plover",
        "value": "Crab-Plover"
    },
    {
        "id": "Larus sabini",
        "label": "Sabine`s Gull",
        "value": "Sabine`s Gull"
    },
    {
        "id": "Vanellus gregarius",
        "label": "Sociable Lapwing",
        "value": "Sociable Lapwing"
    },
    {
        "id": "Oenanthe isabellina",
        "label": "Isabelline Wheatear",
        "value": "Isabelline Wheatear"
    }
]

read the documentation for more information.

If you need to implement more complex scenario and send some additional data to the server or convert the server response in any way you can use custom source callback function. In the case you should use source: function(request, response) {/*your implementation*/}, where the request would be an object having term property (request.term). Inside of your implementation your should make ajax request to the server manually. The response would be callback function which you should call after your custom ajax request will be finished (inside of success event handler). The response function should be called with the parameter which should be array in the same format as mygetUniqueNames returns. I recommend you to examine the source code from the jQuery Autocomplete demo.

To de able to provide unique data from one column of tabele you should just use SELECT DISTINCT SQL statement which are supported in the most databases.

I hope that my description would help you.

UPDATED: If you have the local source the solution you could find in my old answer which you already use. What you just need to do is to call the filterToolbar after the source array are filled. Because you load the data from the server your should move the call of filterToolbar inside of loadComplete. You use loadonce:true jqGrid option which switch the datatype from 'json' to 'local' after the first data loading. So you can include in the loadComplete event handler of your grid the code like the following:

var grid = $('#list');
grid({
    url:'autocompleteTest.php',
    datatype: 'json',
    loadonce: true,
    // ... other parameters
    loadComplete: function(data) {
        if (grid.getGridParam('datatype') === 'json') {
            // build the set 'source' parameter of the autocomplete
            grid.jqGrid('setColProp', 'name', {
                searchoptions: {
                    sopt:['bw'],
                    dataInit: function(elem) {
                        $(elem).autocomplete({
                            source:mygetUniqueNames('name'),
                            delay:0,
                            minLength:0
                        });
                    }
                }
            });
            mygrid.jqGrid('filterToolbar',
                          {stringResult:true,searchOnEnter:true,
                           defaultSearch:"bw"});
        }
    }
});

If you will need to reload the data from the server (change the datatype to 'json' and call grid.trigger('reloadGrid')) you will have to change the code above so that you first destroy the autocomplete widget with $('#gs_name').autocomplete('destroy') and then create it one more time with the same code like inside of dataInit.

这篇关于使用 json 数据自动完成的 jqGrid 工具栏搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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