0

我正在尝试提取从下面引用的 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 名称填充文本框?

我非常感谢大家提前的帮助!

4

1 回答 1

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/

于 2013-05-09T20:24:21.863 回答