【问题标题】:Autocomplete with JQuery plugin使用 JQuery 插件自动完成
【发布时间】:2013-11-11 08:04:48
【问题描述】:

我想从 URL 获取 JSON 响应并将其用作自动完成功能,但我不明白如何接收该 JSON 数组。
我想把响应放到一个 jQuery 插件上。

$('#tags').tagsInput({    
  autocomplete_url:'http://myserver.com/api/autocomplete',
  autocomplete:{selectFirst:true,width:'100px',autoFill:true}
});

将用作 url 的我的 grails 操作:

def getCategories() {
        def categories=Categories.executeQuery("select name from Categories where name like '%"+params.term+"%'",[max:10]);
        JSONArray catArray = new JSONArray(categories);
        render  model:[catArray:catArray]
    }

现在我希望将该 url 响应分配给 autocomplete_url。 虽然当我使用工作正常的手动数组时:

$('#tags').tagsInput({    
  autocomplete_url:myJsonArray,
  autocomplete:{selectFirst:true,width:'100px',autoFill:true}
});

【问题讨论】:

    标签: jquery json grails


    【解决方案1】:

    在不知道 JQuery 插件名称的情况下,我假设 autocomplete_url 可以是 url 或 JSON。如果你想直接设置 JSON,你需要在一个动作中完成:

    动作

    def show() {
      ...
      def categories=Categories.executeQuery("select name from Categories where name like '%"+params.term+"%'",[max:10]);
      String jsonCateg = categories as JSON //transforms your query result to array.
      render view: 'show', model: [domainInstance: domainInstance, jsonCateg: jsonCateg]
      ...
    }
    

    查看

    $('#tags').tagsInput({    
      autocomplete_url:${jsonCateg},
      autocomplete:{selectFirst:true,width:'100px',autoFill:true}
    });
    

    如果要设置操作的 url,请使用 createLink 标签:

    $('#tags').tagsInput({    
      autocomplete_url: '${createLink(controller: "myController", action:"getCategories")}',
      autocomplete:{selectFirst:true,width:'100px',autoFill:true}
    });
    

    并且控制器动作应该直接渲染 JSON:

    def getCategories() {
        def categories=Categories.executeQuery("select name from Categories where name like '%"+params.term+"%'",[max:10]);
        render categories as JSON
    }
    

    【讨论】:

    • 谢谢哥们,我也采用了同样的方法。
    猜你喜欢
    • 1970-01-01
    • 2011-02-13
    • 2011-06-06
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多