我无法让我的AJAX / PHP工作。如果有人能帮助我发现我正在制作的错误,我真的很感激。
以下是我的第一个文件的摘录,它成功填充了HTML中的选择:
<?php
include 'connect_db.php';
//get all period types data
$sql = "SELECT * FROM periodtypes ORDER BY period_type_id";
$result = mysqli_query($connect,$sql);
$rowCount = mysqli_num_rows($result);?>
选择的HTML / PHP:
<select id="period_type_id" name="period_type_id" onchange="getNewP();">
<option value="">Select a Period Type</option>
<?php
if($rowCount>0){
while ($row=mysqli_fetch_assoc($result)){
echo '<option value="'.$row['period_type_id'].'">'.
$row['period_type_desc'].
' </option>';
}
}else{
echo '<option value="">Period type not available</option>';
}
?>
</select>
我希望使用下面的AJAX函数更新输入的HTML:
<label>Start Date (Auto-generated):</label>
<input type="text" id="start_date" name="start_date" value = "" readonly>
<br><br>
<label>End Date (Auto-generated):</label>
<input type="text" id="end_date" name="end_date" value = "" readonly>
AJAX功能:
function getNewP(){
var id = $("#period_type_id").val();
alert(id); //This fires ok
if (id != '')
{
$.ajax({
url: "get_period_nbrs.php",
method:"POST",
data: { id : id },
dataType: "JSON",
success: function(output)
{
$('#start_date').text(output.start_date);
$('#end_date').text(output.end_date);
}
});
}else
{
alert("Please select a Period Type");
}
}
最后,主要的PHP脚本:
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id'])){
//echo $_POST[id];
$sql = "SELECT SUBSTRING(MAX(period_nbr),5,2)+1 AS nxt_sfx,
MAX(start_date)+ 1 as start_date, MAX(end_date)+1 AS end_date
FROM periods AS p
INNER JOIN periodtypes AS pt on pt.period_type_id = p.period_type_id
WHERE p.period_type_id = '".$_POST['id']."'";
$result = mysqli_query($connect,$sql);
while($row=mysqli_fetch_array($result)){
if($result == true){
$start_date = $row['start_date'];
$end_date = $row['end_date'];
$period_nbr_nxt_sfx = $row['nxt_sfx'];
if ($period_nbr_nxt_sfx < 52 && $period_nbr_nxt_sfx != NULL){
$output['start_date'] = $row['start_date'];
$output['end_date'] = $row['end_date'];
echo json_encode($output);
}
}
}
}
?>
答案 0 :(得分:0)
您没有使用正确的方法填写输入信息:
$('#start_date').text(output.start_date);
$('#end_date').text(output.end_date);
应该是:
$('#start_date').val(output.start_date);
$('#end_date').val(output.end_date);
答案 1 :(得分:0)
JSON需要一个根密钥,试试这个:
print_r( "{\"data\": ".json_encode($output)."}" );
而不是
echo json_encode($output);