Jquery autocomplete with php source

2019-08-29 20:40发布

问题:

I would like to use the jquery autocomplete "function" with a php file as the source. I don't get why it is not working. If I use data entered in a variable everything works fine. Hope someone can help. Thank you in advance for your replies. Cheers. Marc.

My HTML:

<input id="moi" type="text"/>

My JS :

$(function() {
        $( "#moi" ).autocomplete({
            source: "php/search_loc.php",
            minLength: 2
        });
    });

My PHP:

<?php
header('Content-Type: text/html; charset=utf-8');
require("../inc/connect.inc.php");
mysql_set_charset('utf8'); 

$result = mysql_query("SELECT * FROM search_loc");
$row=mysql_fetch_assoc($result);

while($row=mysql_fetch_assoc($result)){
    echo $row['srl_loc'].'<br>';}

?>

回答1:

Your PHP script should return JSON data,

In the Jquery UI autocomplete doc

The datasource is a server-side script which returns JSON data,


回答2:

Wrap it in a json_encode() function:

echo json_encode($row['srl_loc']).'<br />';