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

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

问题描述

我发现由奥列格的非常漂亮的演示(http://www.ok-soft-gmbh.com/jqGrid/FillToolbarSearchFilter.htm),它显示了一个自动完成与工具栏的jqGrid使用搜索本地数据,但有惹上麻烦这通过AJAX的JSON工作。是否有一个很好的理由自动完成功能将无法正常工作 - 即使我强迫网格可装载后局部

  $(文件)。就绪(函数(){    VAR mygrid = $(#MYLIST),
    mygetUniqueNames =功能(COLUMNNAME){
        VAR文本= mygrid.jqGrid('getCol',COLUMNNAME),uniqueTexts = [],
            textsLength = texts.length,文字,textsMap = {},我;
        对于(i = 0; I< textsLength;我++){
            文字文本= [I]
            如果(文字==不确定和放大器;!&安培; textsMap【正文】===未定义){
                //测试文本是否是独一无二的,我们把它在地图上。
                textsMap [文字] =真;
                uniqueTexts.push(文本);
            }
        }
        返回uniqueTexts;
    };    mygrid.jqGrid({
            网址:'autocompleteTest.php',
            数据类型:JSON
            colNames:['名','市','stateCd'],
            colModel:
                    {名称:'名',索引:'名',宽度:225,搜索:真正},
                    {名称:'市',索引:城市,宽度:125},
                    {名称:'stateCd',索引:stateCd',宽度:75},
                  ]         的rowNum:100,
        loadonce:真实,
         sortname:'名',
        排序顺序:递减,
         排序:真实,
        viewrecords:真实,
        rownumbers:真实,
        排序顺序:递减,
        IGNORECASE:真实,
        呼叫器:#mypager',
        高度:自动,
        标题:如何更好地使用filterToolbar从服务器数据
    })。的jqGrid('navGrid','#mypager',
              {编辑:假的,加:假的,德尔:假的,搜索:假的,刷新:假});    mygrid.jqGrid('setColProp','名',
            {
                sea​​rchoptions:{
                    SOPT:['体重'],
                    dataInit:功能(ELEM){
                        $(ELEM).autocomplete({
                            来源:mygetUniqueNames(名称),
                            延迟:0,
                            的minLength:0
                        });
                    }
                }
            });    mygrid.jqGrid('filterToolbar',
            {stringResult:真的,searchOnEnter:真的,defaultSearch:BW});    });


解决方案

这是很难在远程源使用的情况下,提供一个例子 jQuery UI的自动完成参数。主要的问题是,你的问题是有关的jqGrid即纯JavaScript 解决方案。如果我们将讨论的塔解决方案的服务器部分,我们将有太多的选择。许多用户使用不同的语言:Java和C#,VB,PHP等。比如我个人preFER C#。然后,我们将不得不选择我们使用的技术:ASP.NET MVC,WCF,ASPX web服务等。比如我会选择WCF。那么,我们应该定义数据库访问技术,例如,实体框架,LINQ到SQL, SqlDataReader的的SqlDataAdapter 等上。让我们我会选择实体框架,并会为您提供相应的code例子,但它会帮助你不是真的,如果你使用例如PHP和MySQL。

所以,我只是描述了接口应该有一个远程源jQuery UI的自动完成的参数服务器没有任何code

您应该在我的例子参数替换成您的服务器的URL类似以下内容:

  dataInit:功能(ELEM){
    $(ELEM).autocomplete({
        来源:yourSearchUrl.php',
        的minLength:2
    });
}

如果用户键入两个字符(该值可以通过的minLength 更改选项),例如'AB',那么自动完成将HTTP GET与参数<请求code> =一词AB :

  yourSearchUrl.php?长期= AB

您的服务器应在相同的格式作为本地源JSON数据回答。我用我的previous例如字符串数组格式。另一个支持的格式与标签/值/既属性的对象数组像

  [
    {
        ID:Dromas池鹭
        标签:蟹鸻
        值:蟹鸻
    },
    {
        ID:鸥sabini
        标签:Sabine`s鸥
        值:Sabine`s鸥
    },
    {
        ID:学名:Vanellus gregarius
        标签:善于交际麦鸡
        值:珩田凫
    },
    {
        ID:水芹雪蛤,
        标签:沙䳭
        值:沙䳭
    }
]

文档了解详情。

如果您需要实现更复杂的场景和一些额外的数据发送到服务器或转换以任何方式可以使用自定义源的回调函数服务器响应。在这种情况下,你应该使用来源:功能(请求,响应){/ *你的实现* /} ,其中要求将是具有物属性( request.term )。你的内部实现你应该Ajax请求手动服务器。您的自定义Ajax请求后的响应将回调函数,你应该调用的 的将完成(在成功<中/ code>事件处理程序)。在响应函数应该用应该是在相同的格式为 mygetUniqueNames 返回数组参数来调用。我建议你​​检查从jQuery自动完成源$ C ​​$ C 演示

要取消能够从tabele你应该只使用 SELECT这是在大多数数据库支持DISTINCT SQL语句,一列提供唯一的数据。

我希望我的介绍能帮助你。

更新时间::如果你有本地源的解决方案,你可以在找到<一个href=\"http://stackoverflow.com/questions/5328072/can-jqgrid-support-dropdowns-in-the-toolbar-filter-fields/5329014#5329014\">my你已经使用旧的答案。你只需要做的是调用 filterToolbar 后,源阵列都充满​​。因为你从服务器加载数据您应该移动的 filterToolbar 里面 loadComplete 。您可以使用 loadonce:真正的的jqGrid其切换数据类型选项'JSON'本地第一个数据加载后。所以,你可以包括在 loadComplete 事件的处理程序的电网code这样的:

  VAR电网= $('#名单');
格({
    网址:'autocompleteTest.php',
    数据类型:JSON,
    loadonce:真实,
    // ...其他参数
    loadComplete:功能(数据){
        如果(grid.getGridParam('数据类型')==='JSON'){
            //建立自动完成的一套源参数
            grid.jqGrid('setColProp','名',{
                sea​​rchoptions:{
                    SOPT:['体重'],
                    dataInit:功能(ELEM){
                        $(ELEM).autocomplete({
                            来源:mygetUniqueNames(名称),
                            延迟:0,
                            的minLength:0
                        });
                    }
                }
            });
            mygrid.jqGrid('filterToolbar',
                          {stringResult:真的,searchOnEnter:真实,
                           defaultSearch:BW});
        }
    }
});

如果您需要从服务器重新加载数据(修改数据类型'JSON'和呼叫 grid.trigger('reloadGrid')),你将不得不改变以上,让你先摧毁自动完成小部件 $('#gs_name')。自动完成('摧毁'),然后用同样的code像里面创造一个更多的时间 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天全站免登陆