我想使用AJAX和Jquery以POST方法将数据传递给我的控制器。
看起来像这样:https://jsfiddle.net/10bhsd2o/
我有引导程序下拉列表,显示数据库中的记录。
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Your Sites <span class="caret"></span></a>
<ul class="dropdown-menu">
<li ><a href="#"><?php
foreach($sites as $site)
{
echo "<li class='specialLink' id='$site->site_key'>".$site->site_key."</li>";
}?></a></li>
</ul>
</li>
现在我想将数据发送到我的控制器,我从
<li></li>
标记的下拉列表中选择该项目。这是我的脚本:
<script type="text/javascript">
$( ".specialLink" ).click(function() {
var value = this.id;
var url= "<?php echo base_url('customer/dashboard/index') ?>";
alert(url)
//get value for throw to controller
alert(value);
$("#specialLink").submit(function(){
$.ajax({
type: "POST", //send with post
url: "<?php echo base_url('customer/dashboard/index') ?>",
data: {value:value},
success:function(data){
alert(data)
}
});
});
});
</script>
生成HTML
<ul class="dropdown-menu">
<li ><a href="#"><li class='specialLink' id='54th-65hy'>54th-65hy</li><li class='specialLink' id='HT45-YT6T'>HT45-YT6T</li></a></li>
</ul>
控制者
public function index()
{
var_dump($_POST);
print_r($_POST);
$this->data['subview'] = 'customer/dashboard/index';
$this->load->view('customer/_layout_main',$this->data);
}
现在我的警报是正确的,我在警报中获取了正确的URL,在警报中获取了正确的数据。
但是在我的控制器中,当我执行print_r($ _ POST);我得到空白数组为什么?我要去哪里错了?
最佳答案
更改您的html
标记。因为你在锚内循环
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Your Sites <span class="caret"></span></a>
<ul class="dropdown-menu">
<?php
foreach($sites as $site)
{
echo "<li class='specialLink' id='$site->site_key'><a href='#'>".$site->site_key."</a></li>";
}
?>
</ul>
</li>
然后更改您的
click
函数 $( ".specialLink" ).click(function() {
var value = this.id;
var url= "<?php echo base_url('customer/dashboard/index') ?>";
alert(url)
//get value for throw to controller
alert(value);
$.ajax({
type: "POST", //send with post
url: "<?php echo base_url('customer/dashboard/index') ?>",
data: {value:value},
success:function(data){
alert(data)
}
});
});
我不知道您是否将
index
函数用于其他视图,但仅用于测试目的。先尝试一下 public function index()
{
if(!empty($_POST)){
var_dump($_POST);
print_r($_POST);
}else{
$this->data['subview'] = 'customer/dashboard/index';
$this->load->view('customer/_layout_main',$this->data);
}
}
让我知道您在第三个警报中得到了什么