我使用jquery从mysql db获取数据。问题是我希望以分离的形式从php获取数据,例如来自php的分段号,名称和父名的separte字段。看一下代码
html和jquery:
<div id="Name"> </div>
<div id="Fname"> </div>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"> </script>
<script>
$('input#rsubmit').on('click', function () {
var rnum = $('input#rollno').val();
if ($.trim(rnum) != ''){
$.post('newdata.php', {rnum: rnum}, function(data){
$('div#Name').text(data);
});
}
});
</script>
</body>
PHP:
if (isset($_POST['rnum']) === true && empty($_POST['rnum']) === false){
$rollno = $_POST['rnum'];
$query = $con->query("select * from students where RollNo='$rollno'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if ($result == true){
echo "Name: ".$result['Name'];
echo "Father Name: ".$result['FatherName'];
}else{
echo "No result found";
}
}
问题是我想在单独的div中使用Name和Father Name。目前,它在#name div
中提供了姓名和父亲姓名答案 0 :(得分:1)
尝试从php返回json。
$user = array();
$result = $query->fetch(PDO::FETCH_ASSOC);
$user['name'] = $result['name'];
$user['father_name'] = $result['FatherName'];
echo json_encode($user);
它将返回[{name:'abc',father_name:'xyz'}] 现在,您可以随时随地访问此json数据。
答案 1 :(得分:0)
将PHP改为以下
if (isset($_POST['rnum']) === true && empty($_POST['rnum']) === false){
$rollno = $_POST['rnum'];
$query = $con->query("select * from students where RollNo='$rollno'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if ($result == true){
echo json_encode($result);
}else{
echo json_encode('No Records found');
}
}
答案 2 :(得分:0)
PHP:
if ($result == true){
echo json_encode(array('name'=> $result['Name'], 'father' => $result['FatherName']));
}else{
和
JS:
$.post('newdata.php', {rnum: rnum}, function(data){
$('div#Name').text(data.name);
$('div#Fname').text(data.father);
});