Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

javascript - Getting jQuery autocomplete to work with PHP source

I have a jQuery autocomplete field with this code:

 var tags = ["a", "ab", "abc", "abcd", "adbce", "abcdef", "abcdefg", "abcdefgh", "abcdefghi", "abcdefghij", "abcdefghijk", "abcdefghijkl", "abcdefghijklm", "abcdefghijklmn", "abcdefghijklmno", "abcdefghijklmnop", "abcdefghijklmnopq", "abcdefghijklmnopqr", "abcdefghijklmnopqrs", "abcdefghijklmnopqrst", ];
      $("input#name").autocomplete({
        position: {
          offset: "0 -10px",
        },
        source: tags
      });

It worked correctly using the 'tags' array as sample input data.

Now I need to have a set of MySQL query results instead of that sample array. What I did was change the function call to this:

$("input#name").autocomplete({
        position: {
          offset: "0 -10px",
        },
        source: "http://absolutepathtofile/autosuggest.php"
      });

I used an absolute path to be sure I wasn't making some silly mistake there, because I can't get the file's return into the autocomplete. I've been to the jQuery documentation and found some examples of using PHP/MySQL to return results for the autocomplete but I can't get it to work.

This is what I tried in autosuggest.php:

$term = $_REQUEST['term'];
$query = "SELECT * FROM merchants WHERE business_name LIKE '%$term%'";
$result = mysql_query($query);

$k=0;
while($row=mysql_fetch_array($result)){

    $aUsers[$k]=$row['business_name'];
    $k++;

}

echo json_encode($aUsers);

I made it as simple as possible but it didn't work.

Then I tested to see if the JSON was being sent at all so I did this:

$array[0]="test";
$array[1]="test1";

echo json_encode($array);

And it doesn't work. I can't find this problem anywhere, what am I doing wrong? PHP version is 5.3.10 and it has json_encode (used it before).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$.ajax({
     url:"http://absolutepathtofile/autosuggest.php",
     type:"post",
     success:function(html){
         $("#user_phone").autocomplete(
            {position: {offset: "0 -10px"},
            source: html
         });
     }   
});
  • work greate for me and tested

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...