我想使用jQuery和JSON将数据从MySQL数据库加载到PHP页面。当用户从选择框中选择名称时,它会将人员的数据加载到文本字段中。
这是我的HTML代码(选择)
<select name='name' id='name'>
<option value='1'>John</option>
<option value='2'>Marco</option>
<option value='3'>Charles</option>
</select>
我想用人员数据填充的文本字段:
<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>
<?php
include('dbconfig.php');
$id = $_POST['id'];
$query = "select * from person where ID='$id'";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
echo json_encode($data);
?>
Ajax电话:
$.ajax({
type: "POST",
async : false,
url: 'http://test.com/getpersonData.php',
dataType: 'json',
data : {
id : $("#id").val(),
},
success : function(data) {
//What to insert here?
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + " : " + textStatus + " : " + errorThrown);
}
});
我应该为success
函数使用什么代码?
答案 0 :(得分:3)
首先,您应该在Content-type
中回复json_encode
之前设置getpersonData.php
标题:
header("Content-type: application/json");
echo json_encode($data);
在您的成功功能中,您可以执行以下操作:
$("#firstname").val(data.firstname); //firstname is the key of the user's firstname from your mysql query
答案 1 :(得分:1)
我猜你的数据库列名在这里,但也许是这样的
$('#firstname').val(data.firstname);
$('#phonenum').val(data.phonenum);
答案 2 :(得分:-1)
getpersonData.php
<?php
include('dbconfig.php');
$id = $_POST['id'];
$query = "select * from person where ID='$id'";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
header("Content-type: application/json");
echo json_encode($data); ?>
主档
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Load JSON data through jQuery and PHP </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
load_data($('#name').val());
$('#name').change(function(){
load_data($('#name').val());
});
});
function load_data(personid)
{
$.getJSON("getpersonData.php", {id: personid}, function(data){
$('#firstname').val(data['firstname']);
$('#phonenum').val(data['phonenum']);
});
}
</script>
</head>
<body>
<select name="name" id="name">
<option value='1'>John</option>
<option value='2'>Marco</option>
<option value='3'>Charles</option>
</select>
<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>
</body>
</html>