2

私は php を初めて使用します。ドロップダウン リストに問題があります。少し詳しく説明させてください。firstCata と subCata の 2 つのテーブルを含むデータベースがあります。テーブル subCata は firstCata ID を参照します。私の index.php ページには、2 つのドロップダウンを持つフォームがあります。最初はfirstCata用で、2番目はデータベースの最初に基づく値を示しています。私が Ajax.Code を使用して行ったすべてのことは以下のとおりです。問題は、ajax を使用して index.php のタグに 2 番目のドロップダウンを表示したことです。index.php ページで subCata の他の詳細を表示するにはどうすればよいですか?

<head>
<script type="text/javascript">
function getSubCata(str)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("result").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getSunCata.php?q="+str.value,true);
xmlhttp.send();
}
</script>
</head>
<select onchange='getSubCata(this)'>
<?php 
$query=mysql_query("SELECT * FROM firstCata") or die(mysql_error());
while($rec=mysql_fetch_array($query))
{
?>
<option value="<?php echo $rec['firstCata_id'];?>"><?php echo $rec['firstCata_name'];?></option>
<?php } ?>
</select>

私のgetSunCata.phpコードは次のようになります

<?php
mysql_connect('localhost','root','');
mysql_select_db('mainCata') or die(mysql_error());

?>
<select>
<?php
$id=$_GET['q'];
echo $id;
$query=mysql_query("SELECT * FROM subcata where firstCata_id=$id") or die(mysql_error());
while($rec=mysql_fetch_array($query))
{
echo $rec['subCata_name'];
?>
 <option id="a"value="echo $rec['subCata_id'];">
    <?php echo $rec['subCata_name']; ?>
</option>
    <?php
}
?>
</select>
4

1 に答える 1

1

あなたが正しく理解している場合は、2番目の選択ですべてのsubCataデータを印刷する必要があります。では、すべての subCata 値も表示したいのに、なぜそのために ajax が必要なのでしょうか? これが私の解決策です:

// MySQL query
$sql = '
    SELECT
        *
    FROM
        firstCata
    JOIN
        subCata
    ON
        firstCata_id = subCata_id';

jQuery を使用したテンプレート html スクリプト

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    var selects_pair = $('select[name="firstCata"], select[name="subCata"]')
    selects_pair.change(function(){
        // get selected id
        var selected_id = $(':selected', this).val();
        // set another selectd corresponding value
        $('[value="' + selected_id + '"]', selects_pair.not(this)).attr("selected", "selected");
    });
});
</script>

テンプレートの html マークアップ

// looping through the data like this, add foreach cycle as you want

<select name="firstCata">
    <option value="<?php echo $rec['firstCata_id'];?>"><?php echo $rec['firstCata_name'];?></option>
</select>

<select name="subCata">
    <option value="<?php echo $rec['subCata_id'];?>"><?php echo $rec['subCata_name'];?></option>
</select>
于 2012-11-24T08:53:32.290 に答える