[英]How to pass variable from Controller to View with Ajax in Codeigniter?
[英]codeigniter sending a variable from ajax to controller
我目前正在做ajax添加,更新和刪除。 而且我認為我將從刪除開始,因為它是最簡單的方法,希望對其他人有所幫助。
在jquery中(這在$ doc.ready內部,並且事件已正確觸發)
if ($a == "Delete")
{
var postid = $(this).next('.postid').val();
$(this).closest(".todo-content").fadeOut();
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?=base_url()?>.index.php/classes/deletepost",
data: {postid: postid},
async: false,
});
}
在HTML
<form method="post">
<button class="btn" onclick="return confirm('Are you sure to delete this item?')">Delete</button>
<input type="hidden" value="<?php echo $id; ?>" name="postid">
</form>
在控制器中
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
這已經在起作用,但隨后我計划將其添加到ajax中。 我正在嘗試將postid
從ajax傳遞到控制器以刪除此帖子。 fadeout
已經可以使用,但只有Ajax無效。 我對ajax還是很陌生,所以我不知道我要去哪里錯了,我可能還會再問有關crud其他部分的問題。
固定!
問題是$.ajax
的url。 它返回一個垃圾。
所以我在標題中添加了一個腳本
<script type="text/javascript">
var BASE_URL = "<?php echo base_url();?>";
</script>
只需在url:
使用BASE_URL
url:
就像url: BASE_URL+'classes/deletepost',
請嘗試遵循以下步驟:
在Codeigniters視圖中:
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- reading jquery file .. -->
<script type="text/javascript" src="http://localhost/jquery/js_search/jquery.js"></script>
<!--you can write file in extra js file .. it depends on you -->
<script type="text/javascript">
$('#button').click(function(){
// ask for confirmation
var result = confirm("Want to delete?");
// if it is confirmed
if (result) {
// get baseURL and ID using attributes
var base_url = $('#button').attr('baseUrl');
var postid = $('#button').attr('postId');
// make a ajax request
$.ajax({
url: base_url,
type: "POST",
dataType: 'json',
success: function (data) {
if(data){
// Fade out the content id
$('#content_id').closest(".todo-content").fadeOut();
}
}
});
}
});
</script>
在控制器中:
// You just need to delete the post and return a status code of "200"
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.