0

每次更改列表之前,我都会尝试编辑选择列表。我想要做的是将已经存在的列表更改为另一个列表,由一个 php 函数调用,该列表从第一个列表和一个 sql 数据库中生成一个新信息列表。

很难解释,所以这是我的代码:

我的代码的基础

//php & html
....

$cli = lastNameList();       //first list
$tli = firstNameList();   //second list

echo"

$cli
<div id='editHtml'>$tli</div>

";

....

函数 (php)

//the functions

function lastNameList(){

$options="<select id='lastNames'>"; 

$sql="SELECT * FROM lastName";
$result=mysql_query($sql); 

$options.="<option value='blank'>-- last names --</option>" ;
while ($row=mysql_fetch_array($result)) { 

$name=$row["name"]; 

$options.="<option value='$name'>$name</option>"; 
} 

$options.= "</SELECT>";
return "$options";
}


function firstNameList(){

$options="<select id='firstNames' style='margin-right:40px;'>"; 

这里有问题:

$sql="SELECT DISTINCT Name FROM firstName WHERE LastName ='lastNameSelectedGoesHere'";
//how do i get the value of the last name so i could make a query for it?

//using distinct to make sure there are no duplicates

$result=mysql_query($sql); 

$options.="<option value='blank'>-- first name --</option>" ;
while ($row=mysql_fetch_array($result)) { 

$name=$row["Name"]; 
$options.="<option value='$name'>$name</option>"; 
} 

 $options.= "</SELECT>";
return "$options";
}

js(如果重要,在 php 文件中)

echo"  <script type='text/javascript'>
$('#lastNames').change(function() {

 document.getElementById('eTech').innerHTML="; 

 $ll = firstNameList();
 echo"$ll;

});";

所以你可以看到我的js文件在一个php文件中,它确实有效,我试图在那里做的是生成一个新的名字列表来替换旧的,但我失败了......任何人都有答案或建议我应该怎么做?

4

1 回答 1

1

使用 ajax 和 jquery 一点也不复杂!

一个快速肮脏的方法是这样做

<div id="firstName"></div>
<script type='text/javascript'>
$('#lastNames').change(function() {
$('#firstName').load('getfirstname.php?lastname=' + $(this).val());
});
</script>

对于 getfirstname.php 页面

$lastName = mysql_real_escape_string($_GET['lastname']);
$sql="SELECT DISTINCT Name FROM firstName WHERE LastName ='$lastName'";


//using distinct to make sure there are no duplicates

$result=mysql_query($sql); 
$options="<select id='firstNames' style='margin-right:40px;'>";
$options.="<option value='blank'>-- first name --</option>" ;
while ($row=mysql_fetch_array($result)) { 

$name=$row["Name"]; 
$options.="<option value='$name'>$name</option>"; 
} 

 $options.= "</SELECT>";
echo $options;

这是一个非常简单的页面,展示了如何使用 ajax 和 jquery 执行 php 代码。

<?
if(!isset($_GET['value'])):?>
<script src="jquery-1.7.1.js"></script>
<select id="select" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</options>
</select>

<div id="phpoutput"></div>

<script>
    $('#select').change(function() {
    $('#phpoutput').load('?value=' + $(this).val());
    });

</script>
<?else:
    $val = $_GET['value'];
    echo "$val sent to server. $val*3 = " . $val *3;
 ?>
<?endif;?>
于 2012-06-29T05:12:00.577 回答