如何使用Ajax和HTML结构来回显自动完成选项? [英] How to use Ajax and the HTML structure to echo autocomplete options?

查看:108
本文介绍了如何使用Ajax和HTML结构来回显自动完成选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我要创建一个自动填充搜索框.它获取JSON并将其发送到<option> s的HTML5 <datalist>.
  1. I want to create an autofill search box. it gets a JSON and sends them to an HTML5 <datalist> of <option>s.

它工作正常,但不能在值中使用空格!所以它只返回第一个单词.例如,如果jresults.name是放手"-我只会得到放手".

It works fine but it cant use spaces in values! so it just returns the first word. for example, if the jresults.name is "lets go" - I get only "lets".

这样做的最佳方法是什么?

What is the best way doing this?

  1. 这部分:$( "#prod_name_list" ).children().remove();阻止我从列表中选择一个选项.因为它在我键入"键时会删除其中的所有内容,因此我需要一个不同的解决方案.

  1. This part: $( "#prod_name_list" ).children().remove(); prevents me of choosing an option from the list. because it deletes everything in it when I "keyup" so I need a different solution for this.

第二部分是在提交表单后,我想获取对象的选定ID. (jresults.id),我不确定如何通过提交检索它.

The second part is after submitting the form I want to get the id chosen of the object. (jresults.id) and I'm not sure how to retrieve it with the submit.

我的代码:

JS部分:

        $("#prod_name").bind("keyup", function(e) {

            if (e.which <= 90 && e.which >= 48){

                $( "#prod_name_list" ).children().remove();
                var prod_name = $("#prod_name").val();

                $.ajax({
                    method: "POST",
                    url: "<?php echo site_url('kas/search_prod_name'); ?>",
                    data: ({ "prod_name": prod_name }),
                    success: function (result){

                        var jresults = JSON.parse(result);
                        console.log("jresults: "+jresults);

                        var lng = jresults.length;
                        console.log("lng: "+lng);

                        for (var i=0; i<lng; i++) {
                            if (jresults.hasOwnProperty(i)) {
                                  console.log("name: "+jresults[i].name);
                                  $("#prod_name_list").append("<option name=\"prod_id\" id="+jresults[i].id+">"+jresults[i].name+"</option>");
                            }
                        }

                    }
                });

            }

        });

HTML部分(使用codeigniter语法的形式:

HTML part(using codeigniter syntaxes for the form:

<?php 
    $attributes = array('class' => 'prod_name', 'id' => 'prod_name', 'name' => 'prod_name', 'list' => 'prod_name_list');


        echo form_input('prod_name',  'prod Name', $attributes);    
    ?>

    <datalist id="prod_name_list"> 


    </datalist>

推荐答案

此处有一些工作要做,但让我们跳入一个工作示例:

A few things to work on here, but let's jump into a working example: https://jsfiddle.net/Twisty/a2z7e1yb/

我测试过的 HTML :

Name: <input class="prod_name" id="prod_name" name="prod_name" list="prod_name_list" />
<datalist id="prod_name_list">

</datalist>

我建议使用 JQuery :

$(document).ready(function() {
  $("#prod_name").keyup(function() {
    $.ajax({
      method: "POST",
      url: "<?php echo site_url('kas/search_prod_name'); ?>",
      data: {
        "prod_name": $("#prod_name").val();
      },
      success: function(result) {
        console.log(result);
        var options = "";
        $.each(result, function(k, v) {
          console.log("name: " + v.name);
          options += "<option value='" v.name + "'>\r\n";
        });
        console.log(options);
        $("#prod_name_list").html(options);
      }
    });
  });
});

如前所述,您可以使用onKeyPressonKeyUp.我把那件事留给你.

As was mentioned, you can use onKeyPress versus onKeyUp. I leave that up to you.

我用以下测试数据进行了测试:

I did testing with test data that looked like:

[
  {
    "name": "Lets Go"
  }, {
    "name": "Go More"
  }
]

$.each()为此很好.它将遍历每个数组项,并将其Key放入k并将每个对象放入v.然后,我们生成所有选项的字符串,并替换datalist中的所有内容,因此,如果结果集在第一个字符上包含15个选项,则在下一次击键时将其替换为我们得到的任何结果集.

The $.each() works well for this. It will iterate over each array item and place it's Key into k and each object into v. We then generate a string of all the options and replace whatever is inside our datalist So if the result set is 15 options on the first character, it would be replaced ion the next keystroke with whatever result set we get.

使用.remove().append()对于这种类型的应用程序变得很麻烦.您想删除所有选项,或用收到的任何新数据替换它们.在我的工作示例中,当按下一个键时,我们看到:

Using .remove() and .append(), in my mind, becomes cumbersome for this type of application. You want to remove all the options, or replace them, with whatever new data you receive. In my working example, when a key is pressed, we see:

<datalist id="prod_name_list">
  <option value="0">Lets Go</option>
  <option value="1">Go More</option>
</datalist>

我希望这很清楚,对您有所帮助.如果不是,请发表评论并让我知道.

I hope this is clear and helps you out. If it's not, leave a comment and let me know.

更新

我认为您可能未正确使用<datalist>标记.页面加载时应完全填充,而不是在输入文本之后.在此处查看更多信息: https://developer.mozilla.org/en -US/docs/Web/HTML/Element/datalist

I think you may be using the <datalist> tag incorrectly. It should be fully populated when the page loads, not after text is entered. See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

应该这样使用: https://jsfiddle.net/Twisty/a2z7e1yb/2/

<label>Name:
<input class="prod_name" id="prod_name" name="prod_name" list="prod_name_list" /></label>
<datalist id="prod_name_list">
  <option value="Let's Go" />
  <option value="No Go" />
  <option value="Go Back to Bed" />
</datalist>

如果您真的想要使其像JQuery UI的自动完成功能,则可以构建一个<ul><div>,并将结果作为列表包含在其中.按下某个键时将填充此列表,仅显示相关结果.例如,如果按下"L",它将在您的PHP中显示该值,并显示"Let's Go"和其他任何以"L"开头的产品名称.它不同于<datalist>,它在您的列表中查找包含"L"的任何内容.

If you really want to make it like JQuery UI's Autocomplete, you would build a <ul> or <div> with the results as a list inside. This list would be populated when a key is pressed, showing just the relevant results. For example if "L" was pressed it would sen that value to your PHP which would show "Let's Go" and any other product Names that begin with "L". It's different than <datalist> which looks for anything in your List that contains "L".

这篇关于如何使用Ajax和HTML结构来回显自动完成选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆