所以这是场景。我有2次下降。第一个具有onchange
功能,可以在第二个下拉列表中加载数据。它完全正常,但我想使用onchange
函数onload
在第二个下拉列表中加载数据。
这是我的功能:
function fetch_select(val)
{
$.ajax({
type: 'post',
url: '../function/fetch_car_package.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
这是我的下拉列表:
<select name='cItemID' onchange="fetch_select(this.value);">
<?php
$sql = "";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();
foreach($result as $row) {
if ($_SESSION['cItemID'] == $row['Item ID']) {
$selected = "selected";
} else {
$selected = '';
}
echo "<option value='".$row['Item ID']."' $selected>".$row['Item Name']."</option>";
}
?>
</select>
我的ajax处理页面:
if(isset($_POST['get_option'])){
$ItemID = $_POST['get_option'];
$sql = "";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();
foreach($result as $row) {
echo "<option value='".$row['cCLID']."' $selected>".$row['cDescription']."</option>";
}
exit;
}
答案 0 :(得分:2)
我(个人)如果我可以提供帮助,就不喜欢运行内联javascript,因此我只需使用$(document).ready()
进行加载,.on('change')
进行更改行动,都利用相同的功能:
<script>
// I am making an object for ajax reuse. You don't necessarily have to have this...premise is the same.
var Ajaxer = function($)
{
var $j = $;
var useUrl = '../function/fetch_car_package.php';
var url;
this.setUrl = function(url)
{
useUrl = url;
return this;
}
this.ajax = function(data,func)
{
$j.ajax({
type: 'post',
url: useUrl,
data: data,
success: function (response) {
func(response);
}
});
}
}
// When document loads
$(document).ready(function() {
// Create ajax instance, pass jQuery
var nAjax = new Ajaxer($);
// Set the send function
function getSelect(obj)
{
// Save the value
var val = obj.val();
// Run the ajax
nAjax.ajax({
"get_option":val
},
function(response){
// Send data to our container
$("#new_select").html(response);
}
);
}
// On load, save our select object
var SelectMenu = $('select[name=cItemID]');
// Run the function on load
getSelect(SelectMenu);
// On change, run the function
SelectMenu.on('change',function(e) {
// Use $(this) to reference itself
getSelect($(this));
});
});
</script>
答案 1 :(得分:1)
尝试添加 计数器 变量,以跟踪<option>
次迭代中的第二个foreach
:
<select name='cItemID' >
<?php
$sql = $store ="";
$sth = $dbh->prepare($sql);
$sth->execute();
$count=0;
$result = $sth->fetchAll();
foreach($result as $row) {
$count++;
if ($_SESSION['cItemID'] == $row['Item ID']) {
$selected = "selected";
}
else {
$selected = '';
}
$store = ($count==2)? "fetch_select(this.value)" : " ";
echo "<option onselect='".$store."' value='".$row['Item ID']."' $selected>".$row['Item Name']."</option>";
}
?>
</select>
如果$store
值达到2,则会添加包含所需javascript的字符串$count
,否则会离开onselect=" "
,
如果选择第二个选项,它将触发具有所选值的函数。
您可以使用onfocus
或onclick
或<option>
标记上的任何其他javascript活动来完成您的工作。