在 Laravel 5.2 上的 post 请求中传递 Algolia id 属性而不是 Name Atributre

pass Algolia id attribute instead of Name Atributre in a post request on Laravel 5.2

使用 Jeffery Way 和 Algolia 文档显示的 Javascript、Vue.js 和 Typeahead.js 方式从 Algolia 平台索引 json 对象。

目前,当我搜索我需要的结果并点击提交按钮时,它在 post 请求中传递名称属性。

如何传递名称和 id 属性,或者如果需要,只传递 ID 属性就可以了。

<script>
new Vue({
    el: 'body', 
    data: {     
    query: '',
    users: []       
    },  
ready: function(){
this.client = algoliasearch("MYID", "MYAPI");
this.index = this.client.initIndex('dev_category_list');
$('#typeahead').typeahead(null, {   
    source: this.index.ttAdapter(),
    displayKey: 'name'
});
},
  methods: {
    search: function(){
        if (this.query.length < 3) return;
    this.index.search(this.query, function(error, results){
    this.users = results.hits;
    }.bind(this));
    }     
}  
})
</script>

作为 laravel、vuejs 和 javascript 的新手,在解释文档中的说明时使用的语法和短语有点难以掌握,因此我们将不胜感激.

我的索引对象如下所示:

{
  "id": "3",
  "name": "My Product 3",
  "value": "3",
  "alternative_name": "Prod 3",
  "objectID": "3"
}

我希望在用户 select 从 algolia 下拉菜单中输入给定结果并点击提交后,在 post 请求中传递 ID 或 objectID 的值以及名称属性, 如果不可能的话,只有 ID 会像上面提到的那样工作。

谢谢。


--- 更新引用 Jerska:---

好的,在作为新手玩了一会儿之后,我似乎已经开始工作了,我不确定这有多安全,或者有人会说有多可靠,希望我离我需要的地方不远一百万英里成为。很高兴看到您的个人和专业想法。

.on('typeahead:select', function (e, suggestion) {
   $('#typeahead').change(function() {
    var val = suggestion.id;
    $('#st').val(val);
});

我创建了一个隐藏的输入字段并命名为 'st' 用于演示和更新 algolia 结果 jquery 正在使用 .change 函数将值附加到隐藏的输入字段价值。这样表格就可以按照我最初想要和希望的那样继续和提交,这里的好处是即使用户要 select 来自 algoia 下拉菜单的结果然后继续表格,如果他或她决定他们要返回搜索字段并更改它,他们可以在提交表单之前或任何 window.location 是 运行 之前做,我什至想过使用 ajax 或简单地 jquery $.post 但它工作正常 .change

期待听到您的想法。 谢谢

If you want to redirect to an item page, the typeahead:select event gives you the selected option :

$('#your-input')
  .typeahead(/* ... */)
  .on('typeahead:select', function (e, suggestion) {
    window.location = suggestion.url;
  });

来自


您可以通过suggestion参数访问所选对象。你绝对可以使用像

这样的东西
window.location = 'YOUR_URL?id=' + suggestion.id + '&name=' + suggestion.name;

这假设您正在使用 typeahead.js@0.11
typeahead.jsunmaintained, Algolia recommends to use their own fork of typeahead.js@0.10, autocomplete.js

以下是不同的事件名称和处理程序签名,具体取决于您使用的library/version:

  • typeahead.js@0.11: typeahead:select -> function($event, suggestion)
  • typeahead.js@0.10: typeahead:selected -> function($event, suggestion, datasetName)
  • autocomplete.js: autocomplete:selected -> function($event, suggestion, datasetName)