Select2 ajax not showing results
我正在使用 select2 和 ajax 在我的数据库中查询特定分类下的术语,但是当我搜索搜索框时,它只会挂在"搜索"上而没有检索到任何结果。
这是我的html
1 | <select multiple="" name="regions1[]" id="regions1" class="job-manager-multiselect select2-hidden-accessible" required="" tabindex="-1" aria-hidden="true"></select> |
我的 jquery:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | jQuery(function($) { $(document).ready(function() { $("#regions1" ).select2({ ajax: { url:"/ajax/connect.php", dataType: 'json', delay: 250, data: function (params) { return { q: params.term // search term }; }, processResults: function (data) { // parse the results into the format expected by Select2. // since we are using custom formatting functions we do not need to // alter the remote JSON data return { results: data }; }, cache: true }, minimumInputLength: 2 }); }); }); |
和我的 php 代码来查询数据库,我正在寻找分类法"job_listing_region"下的所有术语名称
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <?php $servername ="localhost"; $username ="myusername"; $password ="mypassword"; try { $conn = new PDO("mysql:host=$servername;dbname=mydatabase", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo"Connection failed:" . $e->getMessage(); } // strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial $search = strip_tags(trim($_GET['q'])); // Do Prepared Query $query = $conn->prepare(" SELECT * FROM ( SELECT wp_terms.name FROM wp_terms JOIN wp_term_taxonomy ON wp_term_taxonomy.term_id = wp_terms.term_id WHERE taxonomy = 'job_listing_region' AND count = 0 ) as T" ); // Add a wildcard search to the search variable $query->execute(array(':search'=>"%".$search."%")); // Do a quick fetchall on the results $list = $query->fetchall(PDO::FETCH_ASSOC); // Make sure we have a result if(count($list) > 0){ foreach ($list as $key => $value) { $data[] = array('id' => $value['name'], 'text' => $value['name']); } } else { $data[] = array('id' => '0', 'text' => 'No Products Found'); } // return the result in json echo json_encode($data); |
如您所见,我正在检索我的数据,但搜索只是挂起。
提前致谢。
在此处找到解决方案 How to load JSON data to use it with select2 plugin
需要像这样重新创建我的结果
1 2 3 4 5 6 7 | processResults: function (data) { return { results: $.map(data, function(obj) { return { id: obj.id, text: obj.text }; }) }; } |
所以你需要将
1 2 3 4 5 6 | for(i=0;1<data.length;++i){ var currentObject = data[i]; var id = currentObject.id; var text = currentObject.text; //do what you need to here (Put things in a div, etc) } |
然后,您可以执行以下操作:
1 | document.getElementById("search").innerHTML = document.getElementById("search").innerHTML+"<br />"+id+text; |