Php 当一个输入被填充时,如何使用ajax获取mysql数据
html 现在我的问题是,当我输入姓名时,如何使用ajax获取地址和城市?感谢您的帮助不久前,我对我的项目进行了“实时”搜索,因此这里有一些根据您的需要修改的代码(我假设您的页面上有) 首先,我建议您输入一些id:Php 当一个输入被填充时,如何使用ajax获取mysql数据,php,javascript,sql,ajax,Php,Javascript,Sql,Ajax,html 现在我的问题是,当我输入姓名时,如何使用ajax获取地址和城市?感谢您的帮助不久前,我对我的项目进行了“实时”搜索,因此这里有一些根据您的需要修改的代码(我假设您的页面上有) 首先,我建议您输入一些id: ________________________________________________________ | id |PName | PAddress | PCity | | ----|-------------------
________________________________________________________
| id |PName | PAddress | PCity |
| ----|-------------------------------------------------|
| 1 | John | po box no xyz | Florida |
?????????????????????????????????????????????????????????
获取数据的js函数:
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
});
当然还有getUser.php
文件:
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
}
}
});
}
您需要了解更多关于AJAX、PHP和数据库的知识。嗯,这不是我的答案吗?:如果您遇到任何问题,请自行检查并返回。我使用fetcher.php文件连接数据库并获取著名的sql fetch数组中的行。您应该寻找一个关于此问题的教程,基本上,您需要一个从数据库检索数据的php get函数,使用ajax,您可以使用一个返回此信息的get函数?我正在使用一个名为idCardNo的字段获取名称和地址。当我转到getUser.php?A123456时(因为我将类型更改为GET),我得到了这个消息。但是在我的html文件中,如果使用Name
和permAddr
然后更改$(“#PAddress”).val(data.userData.PAddress),我无法得到结果{“status”:true,“userData”:{“Name”:“Nizar Ibrahim”,“permAddr”:“dhaaruge”}
到$(“#PAddress”).val(data.userData.permAddr)代码>和另一个相应的代码。在SQL
中,将$\u POST
更改为$\u GET
。哦,你应该使用getUser.php?value=A123456
直接获取信息。。我无法让它继续工作。我将所有代码上传到数据库img:
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
});
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
}
}
});
}
<?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);