0

html

<input type="text" name="PName" />
<input type="text" name="PAddress" />
<input type="text" name="PCity" />

mysqlテーブル

 ________________________________________________________
| id  |PName          |  PAddress           |  PCity    |
| ----|-------------------------------------------------|
|  1  | John           |  po box no xyz      |  Florida |
?????????????????????????????????????????????????????????

今私の質問は、名前を入力するときにajaxを使用して住所と都市を取得するにはどうすればよいですか?助けていただければ幸いです

4

1 に答える 1

2

少し前に、私は自分のプロジェクトの「ライブ」検索を行ったので、必要に応じて変更されたコードをいくつか示します (ページにjQueryがあると仮定します)。

まず、入力にいくつかのIDを与えることをお勧めします:

<input type="text" name="PName" id="PName" />
<input type="text" name="PAddress" id="PAdress" />
<input type="text" name="PCity" id="PCity" />

その後、PName フィールドの keyup イベントをバインドできます。

var searchTimeout; //Timer to wait a little before fetching the data
$("#PName").keyup(function() {
    searchKey = this.value;

    clearTimeout(searchTimeout);

    searchTimeout = setTimeout(function() {
        getUsers(searchKey);    
    }, 400); //If the key isn't pressed 400 ms, we fetch the data
});

データをフェッチする js 関数:

function getUsers(searchKey) {
    $.ajax({
        url: 'getUser.php',
        type: 'POST',
        dataType: 'json',
        data: {value: searchKey},
        success: function(data) {
            if(data.status) {
                $("#PAddress").val(data.userData.PAddress);
                $("#PCity").val(data.userData.PCity);
            } else {
                // Some code to run when nothing is found
            }   
        }
    });         
}

そしてもちろんgetUser.phpファイル:

<?php
    //... mysql connection etc.

    $response = Array();

    $response['status'] = false;

    $query = mysql_query("SELECT `PAddress`, `PCity` FROM `Users` WHERE `PName` LIKE '%".$_POST['value']."%' LIMIT 1"); //Or you can use = instead of LIKE if you need a more strickt search

    if(mysql_num_rows($query)) {
        $userData = mysql_fetch_assoc($query);

        $response['userData'] = $userData;
        $response['status'] = true;            
    }

    echo json_encode($response);

幸運を!^^

于 2012-10-14T14:52:31.003 に答える