如何将下拉值(使用ajax)作为变量返回

时间:2014-02-20 07:32:26

标签: javascript php jquery ajax

嗨,请帮我解决这个问题。我想下拉选择的值来反映另一个文本字段。为此,我设置onChange函数并使用ajax返回所选值。我将返回值设置为php变量/ session,以便我可以在整个页面中使用它。该值已成功返回但仅显示。我将其隐藏起来,但不知道如何将其转换为变量。

<select name="txtService" id="txtService" onchange="showService(this.value)">
    <option value="0">Select Service</option>

<?php
    $sql = "select * from tab_service where service_active = 1 Order By service_name";
    $query = $db->ExecuteSelect($sql);
    while ($row = mysql_fetch_object($query)) {
        echo "<option value='".$row->service_id."'>".$row->service_name."</option>";
    }
?>

</select> 
<div id="div1"></div>

我的ajax获取并将所选值返回到div1:

<script type="text/javascript">
    function showService(str) {
        if (str == "") {
            document.getElementById("div1").innerHTML;
            return;
        }
    var xhr = false;
    if (window.XMLHttpRequest) {
        // IE7+, Firefox, Chrome, Opera, Safari
        xhr = new XMLHttpRequest();
    } 
    else {
        // IE5/IE6
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xhr) {
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                document.getElementById("div1").innerHTML = xhr.responseText;
            }
        }
        xhr.open("GET", "booking2.php?q="+str, true);
        xhr.send(null);
    }
}

在booking2.php:

<?php 
session_start();

$vals   =   @$_REQUEST['q'];
$_SESSION['SelectValue']=$vals;
?>
<input type="hidden" name="selectedServID" value="<?php echo $_SESSION['SelectValue'];    ?>">

2 个答案:

答案 0 :(得分:0)

你可以改变:

<select name="txtService" id="txtService" onchange="showService(this.value)">

到此:

<select name="txtService" id="txtService" onchange="showService(this.options[this.selectedIndex].value)">

<强>更新:

    if (str == "") {
        document.getElementById("div1").innerHTML;      // ?!?!?!? what is this doing
        return;
    }

此外:

    xhr.open("GET", "booking2.php?q="+str, true);

最好发送为:

    var uri = encodeURIComponent("booking2.php?q="+str);
    xhr.open("GET", uri, true);

另外,你能告诉我str在函数开头包含什么内容吗?

答案 1 :(得分:0)

session_start();

$vals   =   @$_REQUEST['q'];
$_SESSION['SelectValue']=$vals;
echo $_SESSION['SelectValue'];