javascript - 如何将 id 的动态值传递给我从 json 获取的 jquery?

标签 javascript jquery cakephp cakephp-3.0

我从 json 中获取值并传递给自动完成搜索字段。

[{"id":1,"name":"JAVA"},{"id":2,"name":"cake PHP"},"id":3,"name":"Android"}]

例如,当我点击JAVA时,我想获取JAVA的id,比如www.example.com/1

J查询代码:

<script>
$('#search').typeahead({ 
ajax: '/searchendpoint/search', 
onSelect: function() { 
window.location = "/home/view/" + $(this).val().id; }
});
</script> 

最佳答案

当您想使用对象数组作为源时,您需要提供以下逻辑:

  1. 使用哪个对象属性来匹配用户输入
  2. 使用哪个属性来显示匹配项的文本
  3. 当用户选择一个项目时使用哪个属性

更多信息:

  1. http://api.jqueryui.com/autocomplete/#option-source
  2. http://api.jqueryui.com/autocomplete/#method-_renderItem
  3. http://api.jqueryui.com/autocomplete/#event-select

var tags = [
  {"id":1,"name":"JAVA"},
  {"id":2,"name":"cake PHP"},
  {"id":3,"name":"Android"}
];


$( "#search" ).autocomplete({
  source: function( request, response ) {
          var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
          response( $.grep( tags, function( item ){
              return matcher.test( item.name ); // match user request with item.name
          }) );
      },
  select: function( event, ui ) {
    event.preventDefault();
    $("#search").val( ui.item.name ); // display user selection in textbox

    console.log('selected: ' + JSON.stringify(ui) );
    console.log('execute window.location = "example.com/' + ui.item.id + '"'); // use id of the selected item to generate required URL
    
  }
});

// provide rendering logic for each matched item
$w = $( "#search" ).data("ui-autocomplete");
$w._renderItem = function( ul, item ) {
  //console.log(JSON.stringify(item) );
    return $( "<li>" )
      .attr( "data-value", item.id )
      .append( item.name )
      .appendTo( ul );
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input id="search">

编辑:根据您的评论使用 typeahead.js。

var data =
[
  {"id":1,"name":"JAVA"},
  {"id":2,"name":"cake PHP"},
  {"id":3,"name":"Android"}
];


$(function(){
  var substringMatcher = function(strs) {
    return function(q, cb) {
      var matches, substringRegex;
  
      // an array that will be populated with substring matches
      matches = [];
  
      // regex used to determine if a string contains the substring `q`
      substrRegex = new RegExp(q, 'i');
  
      // iterate through the pool of strings and for any string that
      // contains the substring `q`, add it to the `matches` array
      $.each(strs, function(i, str) {
        if (substrRegex.test(str.name)) {
          matches.push(str);
        }
      });
  
      cb(matches);
    };
  };  

  $('.typeahead').bind('typeahead:select', function(ev, suggestion) {
    console.log('Selection: ' + JSON.stringify(suggestion) );
    console.log('execute window.location = "example.com/' + suggestion.id + '"');
  });

  // passing in `null` for the `options` arguments will result in the default
  // options being used
  $('.typeahead').typeahead({
    hint: true,
    minLength: 1
  }, {
    source: substringMatcher(data),
    display: 'name'
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>

    <div id="prefetch">
      <input class="typeahead" type="text" placeholder="">
    </div>

更多信息:

关于javascript - 如何将 id 的动态值传递给我从 json 获取的 jquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46924970/

相关文章:

javascript - 需要帮助使用增量并在文本框中显示

javascript - 添加另一个新单选按钮时如何保存单选按钮的值

javascript - jVectorMap 样式更改填充类型

php - 如何在 PHP 中上传和插入多张图片?

cakephp - 如何测试从模型调用 CakeEmail

javascript - 如何使用 Contentful 在 Gatsby 中包含轮播组件?

javascript - 动态添加和删除 div 行到字段集,JQuery

javascript - d3 饼图全黑填充,d3.schemeCategory20c 未被调用

javascript - 如何检查某个类是否不存在?

php - CakePHP:如何将 Containable 用于嵌套的 HABTM 模型