我需要一些帮助让AJAX在CodeIgniter项目中工作。基于用户的选择,我想使用AJAX将变量(Agency_Number)发送到我的控制器以执行并在我的视图中返回查询结果。
示例:
我能够成功执行查询并在我的表单中填充程序主机名,但是,当返回信息时,我的选择输入会从页面中消失。我想这是由重新加载我的视图引起的,我认为我不应该首先做这个视图。我不知道如何在不执行此操作的情况下将Program_Host_Name值传递回我的视图。
感谢你们给予的任何帮助!
这是我的观点(create_opportunity.php)
<form submit="opportunity/create_opportunity" id="validation-form" method="POST">
<select id="Agency_Number">
<option value=""></option>
<?php foreach ($agencies as $agency):?>
<option value="<?php echo $agency->Agency_Number;?>"><?php echo $agency->Agency_Number;?></option>
<?php endforeach;?>
</select>
<input type="text" id="Program_Host_Name" value="<?php echo $Program_Host_Name ?>"/>
</form>
这是我在视图中的脚本:
<script type="text/javascript">
$('#Lookup').click(function() {
var AgencyNumber = $('#Agency_Number').val();
if (!AgencyNumber || AgencyNumber == 'Agency_Number') {
alert('Please enter an Agency Number');
return false;
}
var form_data = {
Agency_Number: $('#Agency_Number').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('opportunity/create_opportunity'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('body').html(msg);
}
});
return false;
});
</script>
这是我的控制器(opportunity.php)
function create_opportunity() {
$this->data['agencies'] = $this->ion_auth_model->get_agencies();
if($this->input->post('ajax')) {
$Agency_Number = $this->input->post('Agency_Number');
$agency = $this->ion_auth_model->get_agency($Agency_Number)->row();
$this->data['Program_Host_Name'] = $agency->Name;
$this->data['Address_1'] = $agency->Address_1;
}
$this->data['main_content'] = 'create_opportunity';
$this->load->view('./_blocks/template', $this->data);
}
答案 0 :(得分:0)
我不得不使用json_encode()将关联数组从PHP转换为JSON,然后使用$ .getJSON()返回JavaScript数组。
这是我的工作脚本:
<script type="text/javascript">
$('#Lookup').click(function() {
var AgencyNumber = $('#Agency_Number').val();
if (!AgencyNumber || AgencyNumber == 'Agency_Number') {
alert('Please enter an Agency Number');
return false;
}
var form_data = {
Agency_Number: $('#Agency_Number').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('opportunity/get_agency'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
cache: false,
success: function(data) {
$('#Program_Host_Name').val(data.Program_Host_Name);
$('#Address_Line_1').val(data.Address_1);
},
error: function(thrownError) {
alert(thrownError);
}
});
return false;
});
</script>
这是我的工作负责人:
function get_agency() {
if($this->input->post('ajax')) {
$Agency_Number = $this->input->post('Agency_Number');
$agency = $this->ion_auth_model->get_agency($Agency_Number)->row();
echo json_encode(
array( "Program_Host_Name" => "$agency->Name",
"Address_1" => "$agency->Address_1"
)
);
}
}
感谢您的帮助!