点击链接后,我想在Codeigniter中发送一个帖子:
我的HTML代码:
<a href="<?php echo site_url('clientes/delete/'); ?>" id="<?php echo $id; ?>">Delete</a>
我想使用post方法,因为使用csrf保护更安全。
由于
答案 0 :(得分:0)
来源:http://jsfiddle.net/iam_groot/aaeftkhv/
您需要在html标头中为csrf保护创建一个全局变量:
<script>
var csrf_token_name = "<?php echo $this->security->get_csrf_token_name(); ?>";
var csrf_hash = "<?php echo $this->security->get_csrf_hash(); ?>";
</script>
编辑html链接:
<a href="http://httpbin.org/post" id="5" class="delete" onclick="return false;">Delete row</a>
并添加此javascript代码:
<script>
create_form_post = function(action, fields, target) {
if(target == undefined) {
target = '_self';
}
fields[csrf_token_name] = csrf_hash;
id_form = makeid();
$( '<form method="POST" action="'+action+'" target="'+target+'" id="'+id_form+'" style="display:none !important;"></form>' ).appendTo( "body" );
$.each(fields, function( k, v ) {
$( '<input name="'+k+'" value="'+v+'" type="hidden" />' ).appendTo( "form#"+id_form );
});
return id_form;
}
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 9; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
$(document).ready(function() {
$("a.delete").click(function() {
if(confirm("¿Are you sure?")) {
action = $(this).attr('href');
delete_id = $(this).attr('id');
id_delete_form = create_form_post(action, {id: delete_id});
$("form#" + id_delete_form).submit();
}
});
});
</script>
答案 1 :(得分:0)
使用AJAX
url = '<?php echo site_url('clientes/delete/'); ?>';
$('.delete').click(function(){
clientId = $(this).attr('id');
$.ajax({
type: "POST",
url: url,
data: { clientId: clientId }
});
})
在控制器中
if(isset($_POST['clientId'] {
$clientId = $_POST['clientId'];
} else {
$clientId = 'No data';
}