如何在填充一个输入时使用ajax获取mysql数据

时间:2012-10-14 14:32:11

标签: php javascript sql ajax

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获取地址和城市?任何帮助表示赞赏

1 个答案:

答案 0 :(得分: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字段的键盘事件:

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);
祝你好运! ^^