我想使用 AJAX 和 Jquery 以 POST 方法将数据传递到我的 Controller 。
它看起来像这样:https://jsfiddle.net/10bhsd2o/ 我有显示数据库记录的 Bootstrap 下拉菜单。
<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>
现在我想将数据发送到我的 Controller ,我从 <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>
Controller
public function index()
{
var_dump($_POST);
print_r($_POST);
$this->data['subview'] = 'customer/dashboard/index';
$this->load->view('customer/_layout_main',$this->data);
}
现在我的警报是正确的我在警报中得到正确的 url 我在警报中得到正确的数据。
但是在我的 Controller 中,当我执行 print_r($_POST);我得到空白数组为什么?我哪里错了?
最佳答案
更改您的 html
标记。因为你在 anchor 内循环
<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
函数用于其他 View 但用于测试目的。先试试这个
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);
}
}
让我知道您在第 3 次警报时得到了什么
关于javascript - AJAX jQUERY 将 POST 中的数据传递给 codeigniter Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35666914/