3

オートコンプリート検索機能に使用している JavaScript コードがあり、正常に動作しています。しかし、以下のコードを見ると、検索機能が返すデータはハードコードされており、PHP を使用して MySQL からデータを取得したいと考えています。

以下のコードを変換してPHPクエリを使用してデータMySQLを収集し、結果を使用してjavascriptに渡す方法を誰でも手伝ってくれますか? ありがとうございました。

//<![CDATA[
var a1;
var a2;

function InitMonths() {
    a2.setOptions({ lookup: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(',') });
}

function InitWeekdays() {
    a2.setOptions({ lookup: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(',') });
}

jQuery(function () {

    a1 = $('#query').autocomplete({
        width: 448,
        delimiter: /(,|;)\s*/,
        lookup: 'Andorra,Azerbaijan,Bahamas,Bahrain,Bangladesh,Barbados,Belarus,Belgium,Belize,Benin,Bhutan,Bolivia,Bosnia Herzegovina,Botswana,Brazil,Brunei,Bulgaria,Burkina,etc'.split(',')
    });

    a2 = $('#months').autocomplete({
        width: 448,
        delimiter: /(,|;)\s*/,
        lookup: 'January,February,March,April,May,etc'.split(',')
    });

    $('#navigation a').each(function () {
        $(this).click(function (e) {
            var element = $(this).attr('href');
            $('html').animate({ scrollTop: $(element).offset().top }, 300, null, function () { document.location = element; });
            e.preventDefault();
        });
    });

});
4

4 に答える 4

10

新しい

このオートコンプリート プラグインに基づくhttp://www.devbridge.com/projects/autocomplete/jquery/

JavasSript は次のようにする必要があります。

//Start auto complete
a1 = $("#query").autocomplete({
    serviceUrl:'search.php', //tell the script where to send requests
    width: 448, //set width

    //callback just to show it's working
    onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); } 
});

また、PHP (search.php) は次のようにする必要があります。

///
/*** connect to your DB here ***/
///

//retrieve the search term and strip and clean input
$term = trim(strip_tags($_GET['query'])); 

//try to make user input safer
$term = mysqli_real_escape_string($term);

//build a query on the database
$qstring = "SELECT description as value,id FROM test WHERE description LIKE '%".$term."%'";

//query the database for entries containing the term
$result = mysql_query($qstring);

//array to return
$reply = array();
$reply['query'] = $term;
$reply['suggestions'] = array();
$reply['data'] = array();

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
    //Add this row to the reply
    $reply['suggestions'][]=htmlentities(stripslashes($row['value']));
    $reply['data'][]=(int)$row['id'];
}

//format the array into json data
echo json_encode($reply);

プラグインは、この PHP が提供する以下のような json を想定しています

query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']

これはテストしていませんが、問題ないはずです。


古い回答

ここを参照してください: http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/

まず、jQuery オートコンプリート プラグイン (jQuery UI の一部として jQuery でサポートされているもの) を使用していない場合は、それを設定します。http://jqueryui.com/demos/autocomplete/#remote

システムを完全に作り直す方法を尋ねています。

まず、Ajax を使用して、一致する文字列を PHP 経由でプロキシとしてデータベースに送信する必要があります。次に、PHP が結果を返し、Javascript に読み取らせる必要があります。

したがって、(構成として)使用する必要があります:

a1 = $("#query").autocomplete({
source: "search.php"
width: 448  
});

そして、(あなたのPHPとして)のようなもの

//connect to your database

$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends

$qstring = "SELECT description as value,id FROM test WHERE description LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
        $row['value']=htmlentities(stripslashes($row['value']));
        $row['id']=(int)$row['id'];
        $row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
于 2012-08-31T09:53:54.353 に答える
2

使用したプラグインを使用する代わりに、次のリンクで入手可能なプラグインを使用してください。

Jquery UI オートコンプリート

このプラグインを使用すると、php を使用してデータベースからデータにアクセスできます。必ず効きます。

于 2012-08-31T10:03:43.743 に答える
0

あなたはすでに jQuery プラグインを使用しているので、jQuery を知っていることを前提としています。以下のコードでは、ページをリロードせずにサーバーからデータをロードするために使用されるjQueryメソッドを$.post使用しています(あなたが呼ぶかもしれないようにajax)

$.post('yourphp.php', function(data){
     var obj = JSON.parse(data);
      $('#months').autocomplete({
                width: 448,
                delimiter: /(,|;)\s*/,
                lookup: obj
            });
}); 

あなたのphpで:

<?php
$months = ['jan', 'feb'...'dec'];
echo json_encode($months);
?>

autosuggest に使用している jQuery プラグインがわかりません。ただし、jquery ui または html5 の datalist からオートコンプリートを試してみることをお勧めします。ただし、ブラウザのサポートについてはよくわかりません。しかし、ここに例があります:

<datalist id="yo_list">
<?php foreach(){ //loop through the result of your query here ?>
  <option value="<?php echo $somevalue; ?>"><?php echo $somevalue; ?></option>
<?php } ?>
</datalist>

-コードを実際にテストしていないので、動作しない場合やわからないことがあれば教えてください. 詳細については、メソッドへのリンクを$.postご覧ください: http://api.jquery.com/jQuery.post/

于 2012-08-31T10:03:40.790 に答える