【问题标题】:I can not populate JQuery Autocomplete input with a json request to cakephp我无法使用对 cakephp 的 json 请求填充 JQuery 自动完成输入
【发布时间】:2015-08-30 19:02:17
【问题描述】:

我正在使用 JQuery 自动完成向我的 cakephp 应用程序发送 json 请求,javascript 代码来自 http://jqueryui.com/autocomplete/

  $(function() {
    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    $( "#tag-string" )
  // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).autocomplete( "instance" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        source:function(request, response){ 
          $.getJSON("/articles/getTags/" + request.term + ".json", {
            term : extractLast(request.term)
          }, response);
       },
        search: function() {
          // custom minLength
          var term = extractLast( this.value );
          if ( term.length < 1 ) {
            return false;
          }
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
  });(jQuery);

如果我在 chrome js 控制台上运行 XMLHttpRequests(其中“c”是要搜索的术语)

$.getJSON("/articles/getTags/c.json")

我得到这个回复文本:

responseText: "{↵ "tags": [↵ {↵ "tag": "Calles"↵ },↵ {↵ "tag": "Circulacion"↵ },↵ {↵ "tag": "认知"↵ },↵ {↵ "标签": "Creatividad"↵ }↵ ]↵}"

但输入字段未填充此值。 这就是我在“标签字符串”输入字段中得到的(我上传了一张图片,因为这是解释它的最简单方法)

【问题讨论】:

  • 您共享的屏幕截图,我看到您的输入字段附加了一些内容,可能是结果,但可能由于 CSS 问题不可见。尝试检查输入字段。
  • 感谢@MotsManish,在输入字段或 css 样式表上没有发现任何奇怪的东西。会继续努力
  • 请写一个答案并接受它,不要编辑问题说“已解决”。
  • @RaulMagdalenaCatala 很酷,但请让答案有意义。您的代码生成的响应不在问题中(除非它是 responseText 的东西 - 如果是这样,将其格式化为实际响应),您在答案中使用的变量不在问题中。感谢您对我的第一条评论采取行动。

标签: javascript jquery json jquery-ui cakephp


【解决方案1】:

终于解决了。 发送到 jquery 自动完成的 json 响应必须使用“value”和“label”进行格式化。

var ac = [
{
    label: "One Thing",
    value: "One-Thing"
},
{
    label: "Two Thing",
    value: "Two-Thing"
},      

]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2011-07-11
    • 1970-01-01
    • 2014-05-04
    相关资源
    最近更新 更多