我正在尝试填充第三组单选按钮,作为以下脚本的补充:http : //www.electrictoolbox.com/json-data-jquery-php- radio-buttons/
由于某种原因,我似乎无法用相应的数据填充第三组。它只是保持空白:(
调用该 populateFruittype()函数仅会返回[ ],而populateFruitVariety()正确返回json数据。
populateFruittype()
[ ]
populateFruitVariety()
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>
只需添加:
`fruittype` varchar(50) NOT NULL
并用一些自定义值填充
问题解决了。
.change(function() 必须是 .live('click', function()
.change(function()
.live('click', function()