【发布时间】:2021-03-23 06:47:14
【问题描述】:
我是 ajax 的新手,所以我正在学习,我被困住了,试图到处搜索我需要的东西却无济于事。我有一个包含位置列表的下拉列表。但是,基于另一个下拉列表,我想将默认位置返回到列表中。因此,如果我选择资产 A,它的默认位置将自动填充在下拉列表中,但仍会通过 $locations 列表为我提供选择其他位置的选项。我可以将正确的数据返回给 div,但我不知道如何在下拉列表中填充它。下面是我填充 div 的内容。任何有关如何将其发送到 $locations 列表的下拉列表的帮助,但此值作为默认选择将不胜感激。
下拉菜单
<div class="form-group">
<label class="control-label" for="asset_id" id="asset_id" >
Asset
</label>
<?php
echo $this->Form->input( 'WorkorderAsset.0.asset_id', array(
'type'=>'select',
'data-placeholder'=>'Select An Asset Type From Above...',
'class'=>'chzn-select form-control asset',
'empty' => true,
'id'=>'asset',
'label'=>false,
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation text-
danger"></i></div></div>',
'between' => '<div class="input-group">',
));
?>
</div>
<div class="row">
<div class="col-md-6">
<?php
echo $this->Form->input( 'location_id', array(
'id'=> 'location',
'options'=>$locations,
'class'=>'chzn-select form-control',
'empty' => true,
'z'=>'Select A Location',
'required'=>false,
'between' => '<div class="input-group">',
'after' => '<div class="input-group-addon"><i class="fa fa-exclamation text-
danger"></i></div></div>',
));
?>
<div class="row">
<div class="col-md-6">
$('#asset').on('change', function() {
var id = $('#asset').val();
if (id != "") {
$.ajax({
type: 'POST',
url: '/workorders/workorders/getInfo/'+ id +'.json',
dataType: 'html',
beforeSend: function(xhr) {
$(".overlay").show();
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function( response ) {
console.log(response);
$('#location').html(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
complete: function() {
$(".overlay").hide();
},
});
}
else {
alert("Please select an asset");
}
});
在我的控制器中
public function getInfo($id=null)
{
$locate = $this->request->data = $this->Asset->find('first', array(
'conditions'=>array(
'Asset.id' => $id
),
'contain'=>array(
'Location'=>array(
'fields'=>array('Location.name')
),
)
));
if ($this->request->is('ajax')) {
$this->set( 'locate', $locate);
}
}
在我的 JSON 中
<?php
$location = (!empty($locate['Location']['name'])) ? $locate['Location']['name'] : ' ';
?>
<div >
<? echo "Default Asset Location:" . " " . $location ?>
</div>
【问题讨论】:
标签: php jquery sql ajax dropdown