简体   繁体   中英

Typeahead: Return JSON array with multiple data

I'm using bootstrap's typeahead and I'm wondering how I can return a JSON array with multiple pieces of data for each result.

For example, I want to be able to return two pieces of data for each result, the name and the description . How would this be done?

The only way to do this is using "Multiple Datasets" as mentioned in the following link: http://twitter.github.io/typeahead.js/examples/#multiple-datasets

You'll have to create 2 different sources: one for the "name" and one for the "description".

In case you don't want to search using the "description", then you can use the following code: http://twitter.github.io/typeahead.js/examples/#custom-templates You'll be able to search using the "name" and the description will be displayed next to the name.

This code will make the output to show result from two columns when you type. You have to change only in search.php code, not any other place. Try it and give feedback.

$key=$_GET['key'];  
$mysqli = new mysqli("localhost", "root", "", "yourbd");
/* check connection */
  if ($mysqli->connect_errno) {
      printf("Connect failed: %s\n", $mysqli->connect_error);
      exit();
  }
$mysqli->set_charset("utf8");
$result = $mysqli->query("select * from yourtb where yourcolumn LIKE '%{$key}%'");

 if (!$result) {
die(mysqli_error($mysqli));
}

        $rows = array();
        while($r = mysqli_fetch_array($result)) {

             $rows[] = $r['col1']. ' - ' . $r['col2'];
        }
        echo json_encode($rows);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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