jqGrid 工具栏搜索,使用 json 数据自动完成

发布于 2024-11-07 20:50:51 字数 2257 浏览 0 评论 0原文

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

$(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"});

    });

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"});

    });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青春如此纠结 2024-11-14 20:50:51

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

因此,我只是描述哪个接口应该拥有用于 jQuery UI 自动完成的远程 source 参数的服务器,无需任何代码

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

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

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

yourSearchUrl.php?term=ab

您的服务器应使用与本地源格式相同的 JSON 数据进行应答。我在前面的示例中使用了字符串数组格式。另一种支持的格式是具有 label/value/both 属性的对象数组,例如

[
    {
        "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"
    }
]

阅读文档了解更多信息。

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

为了能够从表的一列中提供唯一的数据,您应该只使用大多数数据库都支持的 SELECT DISTINCT SQL 语句。

希望我的描述对您有所帮助。

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

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"});
        }
    }
});

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文