在$ _GET或$ _POST请求中访问Ajax Javascript变量

时间:2011-12-02 11:37:01

标签: php javascript ajax

我正在尝试使用ajax创建一个链接的选择菜单,它可以正常工作,但问题是当我提交表单时,从ajax查询填充的菜单无法通过POST或GET请求访问。下面是我用来请求服务器通过ajax获取所选State的Cities值的代码。

        <?php require_once("includes/initialize.php");
    if (isset($_POST['submitted'])) {

        $state = $_POST['state'];
        $city  = $_POST['city'];
        echo $state;  // output 1
        echo $city;  // No output
    }

    $state = State::find_all();
    ?>

    <html>
    <head>

    <script type = "text/javascript" src = "js/getcities.js"></script>
    <script type="text/javascript">
    var ajax = new Array();

    function getCityList(sel)
    {
        var state_id = sel.options[sel.selectedIndex].value;
        document.getElementById('city').options.length = 0; // Empty city select box
        if(state_id.length>0){
            var index = ajax.length;
            ajax[index] = new sack();

            ajax[index].requestFile = 'getcities.php?state_id='+state_id;   // Specifying which file to get
            ajax[index].onCompletion = function(){ createCities(index) };   // Specify function that will be executed after file has been found
            ajax[index].runAJAX();      // Execute AJAX function
        }
    }

    function createCities(index)
    {
        var obj = document.getElementById('city'); 
        eval(ajax[index].response); // Executing the response from Ajax as Javascript code  
        //var city = ajax[index].response; 
        //alert("Options are: " + city);
    }

    </script>
    </head>

    <body>

    <form action="test.php" method="post">
    <table>
        <tr>
            <td>State: </td>
            <td><select id="state" name="state" onChange="getCityList(this)">
                <option value="">Select a country</option>
                <?php 
                              foreach ($state as $states) {
                                  echo '<option value="';
                                  echo $states->state_id;
                                  echo '">';
                                  echo $states->state;
                                  echo '</option>';
                              }
                ?>  
                </select>
            </td>
        </tr>
        <tr>
            <td>City: </td>
            <td><select id="city" name="city"  > </select> </td>
        </tr>
            <input type="hidden" name="submitted" value="TRUE"/>
            <input type="image" src="images/submit.jpg" name="submit" id="submit"/>
    </table>
    </form>
    </body>
    </html>

好吧,我需要知道的是,有什么方法可以在变量中捕获select菜单的值,这样我可以在通过POST或GET请求提交表单时使用第二个选择菜单中选择的值吗?感谢

0 个答案:

没有答案