想使用jquery从php获取的json填充datalist

时间:2017-03-23 07:59:22

标签: javascript php jquery json ajax

我想使用jquery从php获取的json填充datalist。

HTML code :index.php

<body>
    <input type='text' id="gpanel" name="gpanel" list='listid' required>
    <datalist id='listid'>
      //i want my options here
   </datalist>
</body>

JQuery代码

<script>
$(document).ready(function() 
{
  $.getJSON("php/ajax.php", function(return_data){
     $.each(return_data.data, function(key,value){
     $("#listid").append(
     "<option value="+value.gpanel+">"+"</option>" //gpanel is the title i want in the values
    ); 
  });
});
</script>

php代码:ajax.php

<?php
include("connection.php");
$result=mysqli_query($conn,"select * from active");//db name
while($rec = mysqli_fetch_assoc($result)) 
{
   $rows[] = $rec;
}
$json_row=json_encode($rows);
echo $json_row;
?>

我不知道我错在哪里!但是数据主义者没有按预期填充。

2 个答案:

答案 0 :(得分:1)

在JQuery中,您试图循环create or replace view q3 (status, name, faculty, starting) as select max(q.starting) as status, q.name, q.faculty, q.starting from q2 q where (starting in (select min(starting) from q2)) or (starting in (select Max(starting) from q2)) group by q.name, q.faculty, q.starting; ...而是使用return_data.data

或者在PHP中,添加$.each(return_data, function(key,value){维度:

data

答案 1 :(得分:0)

那么简单!

HTML代码

<form>
    <h3>Search :</h3><br>
    <input type="text" id="search" list="datalist">
    <datalist id="datalist"></datalist>
</form>

jQuery代码

$("document").ready(()=>{
    $("#search").keyup(()=>{
        let list = $("#search").val();
        $("#datalist").empty();
        if(list!=""){
            $.getJSON("http://localhost/file.php?search="+list,(data)=>{
                $.each(data,(k,v)=>{     
                    $("#datalist").append("<option value="+v.gpanel+"></option>"); 
                });
            });
        }
    });
});

PHP代码file.php

$base = new PDO("mysql:host=URL;dbname=DATABASE_NAME","USER","PASSWORD");
$something = $_GET["search"];
$req = $base->prepare("SELECT * FROM your_table WHERE Row_name LIKE '%".$something."%'");
$req->execute();
$tab = $req->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($tab);