【问题标题】:Ajax call is not given in codeignitercodeigniter 中没有给出 Ajax 调用
【发布时间】:2012-12-20 04:54:21
【问题描述】:
<script type="text/javascript" language='javascript'>
    $('#view_comment').submit(function() {
        alert("msg");   
        var sec={'post_id_for_view_comment' : $("#post_id_for_view_comment").val()}
        $.ajax({
            url: "<?php echo base_url().'index.php/'; ?>post_comment/get_all_comments",
            type: 'POST',                          
            data: sec,
            success: function(msg) {
                alert(msg); 
            }
        });
    });
</script>  

表格

<form id="view_comment" method="post" >
    <input type="hidden" name="post_id_for_view_comment" id="post_id_for_view_comment" value="<?php echo $row->post_id; ?>" /> 
    <input type="submit" id="post_button" value="View Comments" />
</form> 

控制器

public function get_all_comments()
{   
    echo 'OK';  
}   

Ajax 调用未提供给控制器。我在一个页面上有多个表单。

【问题讨论】:

  • 您是错过了 var sec 分号还是只是输入错误?
  • var id = $("#post_id_for_view_comment").val(); ///////////// data: {post_id_for_view_comment : id}
  • 和 var sec 定义的结尾?? @AbhijitShelar

标签: ajax codeigniter


【解决方案1】:

这是实现您需要的新方法:

$('#post_button').click(function(e){
e.preventDefault;
var sec = $('#post_id_for_view_comment').val();
//no need to mention index.php when using site_url() function
 $.post('<?php echo site_url("post_comment/get_all_comments")?>', 
{"post_id_for_view_comment": sec },
         function(data.res == "ok"){ // simple test if it returned ok
         //here you can process your returned data. 
         }, "json"); //**
});

提示:使用来自jquery 的$.post - 是一种ajax 调用。

现在在你的控制器中:

function get_all_comments()
{
//getting your posted sec token.
   $sec = $this->input->post('post_id_for_view_comment'); 
   $data['res'] = "ok";// return anything you like.
// you should use json_encode here because your post's return specified as json. see **
   echo json_encode($data); //$data is checked in the callback function in jquery.
}

真的希望我能帮上忙。

【讨论】:

    【解决方案2】:

    对不起,jquery 还没有准备好。

        $(function(){
            $('#view_comment').submit(function(e) {
            var id = $("#post_id_for_view_comment").val();
            $.ajax({
                 url: "<?php echo base_url()?>index.php/post_comment/get_all_comments",
                 type: "POST",                          
                 data: {post_id_for_view_comment:id} ,
                 success: function(msg) {
                       alert(msg); 
    
                 }
            });
                 e.preventDefault();
            });
         });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      相关资源
      最近更新 更多