我想在单击链接时在 Codeigniter 中发送帖子表单:
我的html代码:
<a href="<?php echo site_url('clientes/delete/'); ?>" id="<?php echo $id; ?>">Delete</a>
我想使用 post 方法,因为使用 csrf 保护更安全。
谢谢
最佳答案
来源:http://jsfiddle.net/iam_groot/aaeftkhv/
您需要在 html header 中创建一个全局变量以进行 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>
关于javascript - 如何在 CodeIgniter 中通过 javascript 发送帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27871011/