我有这个PHP代码来从数据库中选择数据:
<?php
include './database_connect.php';
$ppid=$_POST['selectPatientID'];
$query="SELECT * FROM patient WHERE p_Id='$ppid'";
$result= mysqli_query($conn, $query);
while($row= mysqli_fetch_array($result)){
echo ($row['p_fname']);
echo ' ';
echo ($row['p_lname']);
}
?>
但我需要分别获取p_fname
和p_lname
值。我能做些什么来实现这个目标吗?
这是我的jQuery:
<script>
$(document).ready(function () {
$('#selectPatientID').on('change', function (event) {
event.preventDefault();
// alert("Hi");
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'html',
success: function (result) {
$('#patientName').val(result); //in here, how can I get the p_fname and p_lname separetely and put them in two different input fields?
}
});
});
});
</script>
答案 0 :(得分:0)
你必须json_encode
$row = mysqli_fetch_array($result)){
header('Content-Type: application/json');// header for json encode response
echo json_encode($row);
exit;
你的jQuery ajax代码将是:
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'json',// to receive data into json format
success: function (result) {
alert(result.p_fname);
alert(result. p_lname);
}
});
答案 1 :(得分:0)
你应该尝试一下
<?php
include './database_connect.php';
$ppid=$_POST['selectPatientID'];
$query="SELECT * FROM patient WHERE p_Id='$ppid'";
$result= mysqli_query($conn, $query);
$row= mysqli_fetch_array($result);
echo json_encode($row);
?>
您将查询结果添加到数组$row
中,您json_encode()
并将其作为结果回显
<script>
$(document).ready(function () {
$('#selectPatientID').on('change', function (event) {
event.preventDefault();
$.ajax({
url: "UDPatient.php",
type: 'POST',
data: {selectPatientID: $('#selectPatientID').val()},
dataType: 'html',
success: function (result) {
var jsonResult = JSON.parse(result);
var p_fname = jsonResult.p_fname;
var p_lname = jsonResult.p_lname;
// whatever else
}
});
});
});
</script>
可以解析json结果(或者将dataType设置为&#39; json&#39;或者&#39;)。