简体   繁体   English

jQuery AJAX 尝试使其动态时自动完成不起作用

[英]jQuery AJAX Autocomplete not working when trying to make it dynamic

I have my autocomplete working fine if there is hard coded data being fed into it.如果输入硬编码数据,我的自动完成功能可以正常工作。 My PHP is returning a JSON result.我的 PHP 返回 JSON 结果。 I'm not sure where I am going wrong.我不确定我哪里出错了。

HTML HTML

<div class="form-group bgcolor">
  <label for="send_to">Direct to: </label><input type="text" name="send_to" id="send_to" class="form-control send_to typeahead" placeholder="Leave blank normally">
</div>

Jquery Jquery

        $('.typeahead').typeahead({
          source: {
              groupName: {
               ajax({
                url: 'scripts/order_messaging.php',
                method: 'POST',
                data: JSON.stringify({action: 'autocomplete_to_user', query:query}),
                contentType: 'application/json',
                dataType: 'json',
                success:function(data)
                {
                 result($.map(data, function(item){
                  return item;
                 }));
                }
              })
            },
         },
         debug: true
        });

PHP PHP

//autocomplete user name for user_to
if ( $_POST['action'] == 'autocomplete_to_user' ) {
    $stmt = $pdo->prepare('select * from login where username like :query');
    $stmt->bindValue('query', '%'.$_POST['query'].'%');
    $stmt->execute();
    $result = array();
    while($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
        array_push($result, $user_name->username);
    }
    echo json_encode($result);
}

I think it's this line in my jQuery: data: {action: 'autocomplete_to_user', query:query}, Maybe I have a syntax problem.我认为这是我的 jQuery 中的这一行: data: {action: 'autocomplete_to_user', query:query},也许我有语法问题。

As per jQuery Ajax Documentation , dataType: 'json' evaluates the response as JSON and returns a JavaScript object. As per jQuery Ajax Documentation , dataType: 'json' evaluates the response as JSON and returns a JavaScript object.

You need to stringify your data by using JSON.stringify({action: 'autocomplete_to_user', query:query}) before you send it to PHP.在将数据发送到 PHP 之前,您需要使用JSON.stringify({action: 'autocomplete_to_user', query:query})对数据进行字符串化。 Also, you need to add header Content-Type: 'application/json' that tells you PHP code that request data is JSON.此外,您需要添加 header Content-Type: 'application/json'告诉您 PHP 代码请求数据是 JSON。 You can do this by adding contentType: 'application/json' in your Ajax settings.您可以通过在 Ajax 设置中添加contentType: 'application/json'来做到这一点。

Your final jQuery code would look like this:您最终的 jQuery 代码如下所示:

$('.typeahead').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url: 'scripts/order_messaging.php',
    method: 'POST',
    data: JSON.stringify({action: 'autocomplete_to_user', query:query}),
    contentType: 'application/json',
    dataType: 'json',
    success:function(data)
    {
     result($.map(data, function(item){
      return item;
     }));
    }
  })
 }
});

Refer to jQuery Ajax Documentation for mode details.有关模式的详细信息,请参阅jQuery Ajax 文档 Hope this helps!希望这可以帮助!

EDIT:编辑:

You need to update your PHP code to read JSON.您需要更新您的 PHP 代码以读取 JSON。 Please refer to this link .请参考此链接 Your PHP Code should look like this:您的 PHP 代码应如下所示:

<?php
    // Read the input stream
    $body = file_get_contents("php://input");

    // Decode the JSON object
    $object = json_decode($body, true);
    //autocomplete user name for user_to
    if ( $object ['action'] == 'autocomplete_to_user' ) {
        $stmt = $pdo->prepare('select * from login where username like :query');
        $stmt->bindValue('query', '%'.$object['query'].'%');
        $stmt->execute();
        $result = array();
        while($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
            array_push($result, $user_name->username);
        }
        echo json_encode($result);
    }
?>

In my humble opinion, the documentation has some errors.在我看来,文档有一些错误。 For instance, in the demos , specifically the example Country v2 states例如,在demos中,特别是Country v2示例

A POST request will be sent with data myKey: myValue POST 请求将发送数据myKey: myValue

when in actuality the request being sent in the example is GET , because it depends on the type key of the ajax object of the first source ( country in this case), which is not set, thus defaulting to GET .实际上,示例中发送的请求是GET ,因为它取决于第一个源(在本例中为国家/地区)的ajax object 的type键,未设置,因此默认为GET

So, that being said, you really should stick to the proposed HTML structure (at least start with it, then take away stuff you don't want gradually as long as it'll let you).所以,话虽这么说,你真的应该坚持建议的 HTML 结构(至少从它开始,然后只要它允许你就逐渐拿走你不想要的东西)。

HTML HTML

<form id="form-country_v2" name="form-country_v2">
    <div class="typeahead__container">
        <div class="typeahead__field">
            <div class="typeahead__query">
                <input class="typeahead" name="country_v2[query]" placeholder="Search" autocomplete="off">
            </div>
            <div class="typeahead__button">
                 <button type="submit">
                     <i class="typeahead__search-icon"></i>
                 </button>
            </div>
        </div>
    </div>
</form>

JS JS

$(document).ready(() => {
  $('.typeahead').typeahead({
    template: "{{display}} <small style='color:#999;'>{{group}}</small>",
    source: {
      users: { //might as well be 'willy wonka', it doesn't matter
        ajax: {
          type: "POST",
          url: "scripts/order_messaging.php",

          //this is not actually needed for the request to work (reach the server),
          //this is used to access said request's returned data, it all
          //depends on how you structure the response in the server,
          //check out the php part
          path: "data.users",

          data: {
            action: 'autocomplete_to_user',
            query: 'username'
          }
        }
      }
    },
    callback: {
      //this is just to help you show the response in the html
      onResult: function(node, query, result, resultCount) {
        if (query === "") return;

        var text = "";

        if (result.length > 0 && result.length < resultCount) {
          text = "Showing <strong>" + result.length + "</strong> of <strong>" + resultCount + '</strong> elements matching "' + query + '"';
        } else if (result.length > 0) {
          text = 'Showing <strong>' + result.length + '</strong> elements matching "' + query + '"';
        } else {
          text = 'No results matching "' + query + '"';
        }
        $('#result-container').html(text);

      },
      onInit: function(node) { //and this is just informational
        console.log('Typeahead Initiated on ', node, node.selector);
      }
    }
  });
});

order_messaging.php order_messaging.php

if ($_POST['action'] == 'autocomplete_to_user') {
    $stmt = $pdo->prepare('select * from login where username like :query');
    $stmt->bindValue('query', '%' . $_POST['query'] . '%');
    $stmt->execute();
    $result = array();
    while ($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
        array_push($result, $user_name->username);
    }

    echo json_encode(array(
        "status" => true,
        "error" => null,

        //here you use whatever structure you want to return the data in,
        //as long as the payload is an array ($result).
        //remember in the JS you are expecting 'data.users'?
        //this is where it's coming from
        "data" => array(
            "users" => $result,
        )
    ));
} else
    echo json_encode(array(
        "status" => true,
        "error" => null,
        "data" => array(
            "users" => [],
        )
    ));

HIH HIH

I've tested the library and you need to change two things in order to make it work.我已经测试了该库,您需要更改两件事才能使其正常工作。

1) You need to restructure the source parameter. 1)您需要重组source参数。 You were giving it an AJAX callback which is not supported.你给它一个不支持的 AJAX 回调。 According to the documentation, it accepts an array or an object with settings, so AJAX needs to be defined like this:根据文档,它接受带有设置的数组或 object,因此需要像这样定义 AJAX:

$('.typeahead').typeahead({
    source: {
        // source has an "ajax" property where you just need to place
        // the object with AJAX params (the one you'd normally place inside
        // an $.ajax() call)
        ajax: {
            url: 'scripts/order_messaging.php',
            method: 'POST',
            data: {
                action: 'autocomplete_to_user',
                query: query,
            },
            dataType: 'json',
            path: '',
        },
    },
});

The path property of the ajax object is key here. ajax object 的path属性是这里的关键。 It tells the typeahead function where to look for the data that was returned by the AJAX action.它告诉预先输入的typeahead在哪里查找由 AJAX 操作返回的数据。 Since you're encoding a one-dimensional array of values, you need to set it to an empty string, meaning your data is in the root of the response.由于您正在编码一维值数组,因此您需要将其设置为空字符串,这意味着您的数据位于响应的根目录中。

If you were to return, for example, an array like echo json_encode(['users' => $result]);例如,如果您要返回一个数组,例如echo json_encode(['users' => $result]); then you'd have to set the path to 'users' (because that is the index in the response that holds your data).那么您必须将路径设置为'users' (因为这是保存数据的响应中的索引)。

2) You have to follow a strict HTML structure in order to make it work: 2)您必须遵循严格的 HTML 结构才能使其工作:

<div class="typeahead__container">
    <div class="typeahead__field">
        <div class="typeahead__query">
            <input class="js-typeahead" name="q" autocomplete="off">
        </div>
    </div>
</div>

If you leave out any of these elements, it doesn't trigger the functionality.如果您遗漏任何这些元素,则不会触发该功能。 This HTML structure is one of the first things they mention in the documentation.这个 HTML 结构是他们在文档中提到的第一件事。

Well, after much trial and error I got an autocomplete working using jQuery.autocomplete.好吧,经过多次试验和错误,我得到了一个使用 jQuery.autocomplete 的自动完成功能。

I don't know what I was doing wrong with the typeahead but the documentation was hard to understand (probably because of my limited experience with jQuery).我不知道我在输入前做错了什么,但文档很难理解(可能是因为我对 jQuery 的经验有限)。

To all those in the future that need some help with this;致所有未来需要帮助的人; here is a tutorial I found that was helpful: jquery ui autocomplete tutorial这是一个我发现很有帮助的教程: jquery ui autocomplete tutorial

Thank you to everyone谢谢大家

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM