选择框的AJAX返回值

时间:2012-02-26 00:02:35

标签: php mysql ajax select option

我试图使用AJAX,以便在下拉菜单(模块标题)中选择一个选项时,它接受该值,使用该模块标题对数据库中的所有记录执行SQL查询,然后发布模块代码与模块标题相关,即模块标题:团队项目=模块代码:11COB290。

启动代码:

<td align="center">
<select name='ModuleTitle' id='ModuleTitle' onChange='select_code()' style='width:100%;'>
<option>Select...</option>

    <?php
        //3. Perform database query
        $result = mysql_query("SELECT * FROM Module
        ORDER BY  `ModTitle` ASC;", $connection);
        if(!$result){
            die("Database query failed: " . mysql_error());
        }
        //4. Use Returned Data
        while ($row = mysql_fetch_array($result)) {
            $module = $row[2];
            echo "<option name='{$module}'>{$module}</option><br />";       
        }
    ?>
    </select>
    </td>

    <td align="center">
    <span id="result"></span>


    </select>
</td>

然后是.js文件:

var xmlhttp;

// Give the function a unique name, this is what your HTML will call to run the AJAX
function select_code() {

    // This is all just setting up the variable, ignore it
    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; 

        }

    };

    var val = document.getElementById("ModuleTitle"); 
    var title = val.options[val.selectedIndex].text;


    var parameters = "title=" 
                    + title;


    xmlhttp.open("POST", "ajaxexample2mod.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(parameters);

}

最终的PHP文件(ajaxexamplemod.php):

<?



    <?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php include("includes/headsec.php"); ?>



    <?php
    $title = $_POST['title'];

    //3. Perform database query
    $result = mysql_query("SELECT * FROM Module
    WHERE ModTitle = {$_POST['title']}
    ORDER BY  `ModTitle` ASC;", $connection);
    if(!$result){
        die("Database query failed: " . mysql_error());
    }
    //4. Use Returned Data
    while ($row = mysql_fetch_array($result)) {
        $module = $row[3];
        echo $module;
}       



?> 

1 个答案:

答案 0 :(得分:0)

你需要像

这样的东西
var mydata=xmlhttp.responseText;

然后用mydata变量做一些事情。