我有这种形式,其中有一个浪费:
<b>Please mention Lunch or Dinner or both</b><br/>
<select name="ldb" id="ldb" onchange="coajax();">
<option value=""></option>
<option value="1">Lunch</option>
<option value="2">Dinner</option>
<option value="3">Both</option>
</select>
如果用户选择午餐,那么我想显示下拉列表:
<select name="lunch" id="lunch">
<option value=""></option>
<option value="">10-12pm</option>
<option value="">11-1pm</option>
<option value="">12-2pm</option>
</select>
如果用户选择晚餐,那么我想显示下拉列表:
<select name="dinner" id="dinner">
<option value=""></option>
<option value="">4-6pm</option>
<option value="">5-7pm</option>
<option value="">6-8pm</option>
<option value="">7-9pm</option>
<option value="">8-10pm</option>
</select>
如果用户选择两者,则应显示最后两个下拉列表。 我尝试使用ajax:
<script type="text/javascript">
function coajax()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var q="lunch.php?lid=" + document.getElementById("ldb").value;
xmlhttp.open("GET",q,false);
xmlhttp.send(null);
document.getElementById("lunch").innerHTML=xmlhttp.responseText;
}
</script>
但是我很困惑。我该怎么办?
答案 0 :(得分:1)
通过提交节点使其更简单:
<b>Please mention Lunch or Dinner or both</b><br/>
<select name="ldb" id="ldb" onchange="coajax(this);">
<option value=""></option>
<option value="1">Lunch</option>
<option value="2">Dinner</option>
<option value="3">Both</option>
</select>
<span id="ldb_target"></span>
现在javascript创建跨平台的请求对象:
function RequestObject () {
var ReturnValue = null;
try {
ReturnValue = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (Error) {
try {
ReturnValue = new ActiveXObject("MSXML2.HTTP");
}
catch (Error) {
try {
ReturnValue = new XMLHttpRequest();
}
catch (Error) {
// failed
return null;
}
}
}
return ReturnValue;
}
接下来我们创建事件处理程序:
var requestObj = null;
function coajax(sender)
{
requestObj = RequestObject();
if (requestObj)
{
sender.enabled = false; // so a user cannot change till request finished
requestObj.open('get', 'luch.php?lid=' + sender.value, true);
requestObj.onreadystatechange = coajax_finish;
requestObj.send(null);
}
}
现在我们创建回调处理程序:
function coajax_finish()
{
if (requestObj.readyState == 4)
{
document.getElementById('ldb_target').innerHTML = requestObj.responseText;
document.getElementById('ldb').enabled = true;
}
}
在php方面,这很简单:
<?php
if (!isset($_GET['lid']))
exit;
if ($_GET['lid'] == 1 || $_GET['lid'] == 3)
{
?>
<select name="lunch" id="lunch">
<option value=""></option>
<option value="">10-12pm</option>
<option value="">11-1pm</option>
<option value="">12-2pm</option>
</select>
<?php
}
if ($_GET['lid'] == 2 || $_GET['lid'] == 3)
{
?>
<select name="dinner" id="dinner">
<option value=""></option>
<option value="">4-6pm</option>
<option value="">5-7pm</option>
<option value="">6-8pm</option>
<option value="">7-9pm</option>
<option value="">8-10pm</option>
</select>
<?php
}
?>