2013-01-06 121 views
0
<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> 

形式Ajax調用不笨

<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調用不給控制器給出。我在單頁上有多個表單。

+0

你錯過了var sec分號還是錯了? –

+0

在哪裏放分號? –

+0

'var id = $(「#post_id_for_view_comment」)。val();' '///////////' 'data:{post_id_for_view_comment:id}' –

回答

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"); //** 
}); 

提示:使用$.postjquery - 是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. 
} 

真希望我幫助。

0

對不起,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(); 
     }); 
    }); 
+0

然後我可以在$(document).ready(function()中編寫代碼嗎? –

+0

yes。 http://stackoverflow.com/questions/1191833/how-to-run-a-function-in-jquery –