我正在尝试从下面引用的MySQL查询中提取数据并使用该数据填充相应的文本框:
<?php
header('Content-type: application/json');
$server = "••••";
$username = "••••";
$password = "••••";
$database = "••••";
$username_pull = $_POST['a_username'];
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT uname, pword, fullname, phone_num, email_add, car_details FROM app_login WHERE uname = '$username_pull'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . json_encode($records);
?>
如果我插入$ username_pull =“admin”,我会得到以下json信息,所以我知道它有效:
[{"uname":"admin","pword":"password","fullname":"John Smith","phone_num":"123-456-7890","email_add":"john@website.com","car_details":"2013 Black Cadillac ATS"}]
这是我的json回调函数:
function fillTheGap()
{
var f_uname = $("#a_username").val();
$.ajax({
url: "login2.php",
data: f_uname,
dataType: "jsonp",
jsonp: "jsoncallback",
success: function(data)
{
$("#a_phonenum").val(data.phone_num);
$("#a_fullname").val(data.fullname);
$("#a_email").val(data.email_add);
$("#a_cardetails").val(data.car_details);
},});
}
以下是启动数据提取的表单:
<form name="check_user" method="" action="post">
Your Username:
<input id="a_username" name="a_username" type="text" onBlur="fillTheGap()">
Your Full Name:
<input id="a_fullname" name="a_fullname" type="text">
Your Phone Num:
<input id="a_phonenum" name="a_phonenum" type="text">
<input name="submit" type="button" value="Submit">
</form>
如何使用相应的ID名称填充文本框?
我非常感谢大家的帮助!
答案 0 :(得分:1)
尝试这样的事情:
data = {"uname":"admin","pword":"password","fullname":"John Smith","phone_num":"123-456-7890","email_add":"john@website.com","car_details":"2013 Black Cadillac ATS"}
$.each(data, function(key, value){
$("#a_"+key).val(value);
});
所以你的功能应该是这样的:
function fillTheGap()
{
var f_uname = $("#a_username").val();
$.ajax({
url: "login2.php",
data: f_uname,
dataType: "jsonp",
jsonp: "jsoncallback",
success: function(data)
{
$.each(data, function(key, value){
$("#a_"+key).val(value);
});
}
});
}
你也可以在这里试试: http://jsfiddle.net/nhKks/