我目前正在进行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,
});
}
in 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很新,所以我不知道我哪里出错了,我也可能会再问一些关于其他部分的问题。
答案 0 :(得分:0)
固定!
问题是$.ajax
内的网址。它返回垃圾。
所以我在标题
中添加了一个脚本<script type="text/javascript">
var BASE_URL = "<?php echo base_url();?>";
</script>
只需在BASE_URL
中使用url:
,就像url: BASE_URL+'classes/deletepost',
答案 1 :(得分:0)
请尝试遵循:
在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');
}