我已经工作了一段时间,并在SO上发现了许多线索,但还没有任何工作。我试图通过选择"添加新的"来创建用户可以添加的表单中的动态下拉列表。选项,它会弹出一个模态窗口,可以在其中键入新选项。我使用jquery调出窗口并捕获输入和ajax(希望)发布文本并在php中检索它。我在控制台上看到在javascript中捕获了新选项,ajax发布了帖子,但是post数组是空的。
我的代码全部在视图中。当一个"添加新的"选择弹出的模态窗口,可以输入文本。我想在视图中捕获输入的文本而不提交,并将其显示在更新的选项列表中。
<legend>Animal Info</legend>
<div class="control-group <?php if (form_error('animal_species')) { echo 'error'; } ?>">
<label class="control-label">Species</label>
<div class="controls">
<?php # Add "Add New"
$options = $species + array('addnew' => 'Add New');
echo form_dropdown('animal_species', $options,
set_value('animal_species', (isset($my_data->animal_species)) ? $my_data->animal_species: ''),
'id = "animal_species"',
'class', 'addnew');
echo form_error('animal_species', '<span class="help-inline">', '</span>');
?>
</div>
</div>
<?php
if(isset($new_option))
{
$new_option = $_POST['new_option'];
$species = array($new_option => $new_option) + $species;
var_dump($new_option);
}
?>
<script type="text/javascript">
$('#upload_form option[value="addnew"]').click(function(){
// Show modal window
$('#add-new').modal('show');
$('#add-new-submit').on('click', function(){
// Get new option from text field
var new_option = $('#add-new-text').val();
console.log(new_option);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
data: {new_option:'new_option'}
}).fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: " + textStatus, errorThrown);
});
$('#add-new').modal('toggle');
});
//});
});
</script>
<!-- add-new field -->
<div class="modal small hide fade" id="add-new" tabindex="-1" role="dialog" aria-labelledby="add-new-fieldLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="add-new-fieldLabel">Add New Field</h3>
</div>
<div class="modal-body">
<p>Would you like to add a new item?</p>
<input type="text" id="add-new-text" name="add-new" placeholder="Type the new option">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="add-new-submit" name="add-new-submit"/>Add</button>
</div>
</div><!-- /add-new field -->
现在,字符串new_options在控制台中捕获,但在php中为NULL,因此ajax由于某种原因不发布。这是因为我试图更新同一页面吗?
答案 0 :(得分:1)
将其更改为:
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
dataType: 'text',
data: {new_option : 'new_option'}
}).fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: " + textStatus, errorThrown);
});
如果你能够通过以下方式访问它:
$_POST['new_option'];
PHP中的没有密钥,获取字符串
只需$new_option = $_POST;
答案 1 :(得分:0)
因为您将发布的值视为$_POST['new_option']
..您需要在ajax中将数据对象作为new_option传递...
试试这个
...
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
dataType: 'text',
data:{'new_option':new_option}, //<---here
});
console.log(new_option);
.....