我正在尝试填充第三组radiobuttons作为以下脚本的补充:http://www.electrictoolbox.com/json-data-jquery-php-radio-buttons/
出于某种原因,我似乎无法用相应的数据填充第三组。它只是空白:(
仅调用populateFruittype()
函数会返回[ ]
,而populateFruitVariety()
会正确返回json数据。
getdata.php(数据库连接/获取数据)
<?php
$dsn = "mysql:host=localhost;dbname=mydb";
$username = "username";
$password = "password";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['fruitName'])) {
$stmt = $pdo->prepare("SELECT DISTINCT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['fruitName']));
$rows[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if(isset($_GET['fruitVariety'] )) {
$stmt = $pdo->prepare("SELECT DISTINCT fruittype FROM fruit WHERE variety = ? ORDER BY fruittype");
$stmt->execute(array($_GET['fruitVariety']));
$rows[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Toevoegen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function populateFruitVariety() {
var fruitName = $('input[name=fruitName]:checked').val();
$.getJSON('getdata.php', {fruitName: fruitName}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitVariety" value="' + array['variety'] + '" />' + array['variety'] + '</label> ';
});
$('#varieties').html(html);
});
}
function populateFruittype() {
var fruitVariety = $('input[name=fruitVariety]:checked').val();
$.getJSON('getdata.php', {fruitVariety: fruitVariety}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> ';
});
$('#fruittype').html(html);
});
}
$(function() {
$('input[name=fruitName]').change(function() {
populateFruitVariety();
});
});
$(function() {
$('input[name=fruitVariety]').change(function() {
populateFruittype();
});
});
</script>
</head>
<body>
<form>
<div>
<strong>Fruit:</strong>
<label><input type="radio" name="fruitName" value="Apple"/>Apple</label>
<label><input type="radio" name="fruitName" value="Banana"/>Banana</label>
<label><input type="radio" name="fruitName" value="Orange"/>Orange</label>
<label><input type="radio" name="fruitName" value="Pear"/>Pear</label>
</div>
<div>
<strong>Variety:</strong>
<span id="varieties"></span>
</div>
<div>
<strong>Type:</strong>
<span id="fruittype"></span>
</div>
</form>
</body>
</html>
可以在此处找到数据库查询和内容:http://www.electrictoolbox.com/mysql-example-table/
只需添加:
`fruittype` varchar(50) NOT NULL
并填写一些自定义值。
答案 0 :(得分:2)
问题解决了。
.change(function()
必须是.live('click', function()