[英]AJAX run onchange event before the page load
所以這是場景。 我有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;
}
我(個人)不喜歡運行內聯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>
嘗試添加計數器變量以跟蹤foreach
迭代中的第二個<option>
:
<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>
如果$count
值達到2,它將添加一個包含所需javascript的字符串$store
,否則離開onselect=" "
,如果選擇第二個選項,它將觸發具有所選值的函數。
您可以在<option>
標簽上進行onfocus
或onclick
或任何其他javascript事件,以完成您的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.