需要有关Ajax的帮助

时间:2012-08-22 17:34:06

标签: php javascript ajax onchange

当表单的选择值发生变化时,我正在尝试使用ajax函数。它应该根据所选状态显示城市列表。但是,它没有做任何事情。

cities.php

<script type="text/javascript">
function change_state(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("cityselector").innerHTML=xmlhttp.responseText;
 }
}
xmlhttp.open("GET","changestate.php?changed_state="+str,true);
xmlhttp.send();
}
</script>

<div class="city-switcher">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get" id="cityselector" style="position: absolute; top: 15px; left: 310px;">
    <select name="city" onchange="document.forms['cityselector'].submit()" style="font-size: 1.5em;">
    <?php
    $selected_state = select_single("STATE", "locations", "NAME='$location'", "");
    $cities = select("*", "locations", "STATE='$selected_state'", "");
    foreach ($cities as $city){
        echo '<option value="'.$city['NAME'].'" '.($location == $city['NAME'] ? 'selected="selected"' : '').'>'.$city['NAME'].'</option>';
    }
    ?>
    </select>
</form>
    <select name="state" onchange="change_state(this.value)" style="font-size: 1.5em;">
    <?php
    $states = select("DISTINCT STATE", "locations", "", "ORDER BY STATE ASC");
    $selected_state = select_single("STATE", "locations", "NAME='$location'", "");
    foreach ($states as $state){
        echo '<option value="'.$state['STATE'].'" '.($selected_state == $state['STATE'] ? 'selected="selected"' : '').'>'.$state['STATE'].'</option>';
    }
    ?>
    </select>

 </div>

changestate.php

<?php
 include '../config.php';
 include '../library.php';

 $changed_state = $_GET['changed_state'];

 echo '<select name="city" onchange="document.forms[\'cityselector\'].submit()" style="font-size: 1.5em;">';
 $cities = select("*", "locations", "STATE='$changed_state'", "");
 foreach ($cities as $city){
echo '<option value="'.$city['NAME'].'" '.($location == $city['NAME'] ? 'selected="selected"' : '').'>'.$city['NAME'].'</option>';
 }
 echo '</select>';
 ?>

任何人都可以告诉我我做错了什么。

谢谢,

2 个答案:

答案 0 :(得分:0)

重读后我正在修改我的答案

<select name="state" onchange="change_state(this.value)"

应该是

<select ... onchange="change_state(this.options[this.selectedIndex].value)" ...

答案 1 :(得分:0)

找出问题所在。问题是我的路径错误xmlhttp.open("GET","changestate.php?changed_state="+str,true);

相反它应该是

xmlhttp.open("GET","sections/changestate.php?changed_state="+str,true);