我有两个选择框,想要根据第一个选择框的更改填充第二个选择框。所以我的第一个选择框的代码
<select id="category-box" name="category" onchange="showCrops()" >
<option value ="0">Select category</option>
<?php
$query = $con->query("Select*from categories");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->category_id."'>".$row->category."</option>";
}
?>
</select>
用于ajax调用的onchange函数 function showCrops(){
var name = $('#category-box').val();
$.ajax({
type: "POST",
url: "getCropName.php",
data: {category:name},
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
var opts = $.parseJSON(data);
$.each(opts, function(i,d) {
$('#crop-box').append('<option value="' + d.crop_id + '">' + d.crop_name + '</option>');
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
}
});
}
获取响应的PHP代码
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$category = $_POST['category'];
$sql1 = $con->query("SELECT category_id from categories where category ='".$category."' ");
$row1= $sql1->fetch_array();
$sql2 = $con->query("SELECT * from crop_category where category_id ='".$row1['category_id']."' ");
while($row2 = $sql2->fetch_assoc()){
echo json_encode($row2);
}
json的回应是
{"crop_id":"1","category_id":"1","crop_name":"rice"} {"crop_id":"2","category_id":"1","crop_name":"wheat"}
但是我得到了解析错误&#39;在主要的PHP页面上。我的代码中的问题是什么?我对javascript的了解较少,所以可能需要修正以填充第二个选择框。
答案 0 :(得分:0)
只需更改php代码,即可生成正确的JSON字符串..
$arr = array();
while($row2 = $sql2->fetch_assoc()){
$arr[] = $row2;
}
echo json_encode($arr);