做项目为了防止crsf攻击,将编辑和删除改成了ajax post提交方式,但是不知道怎么在ajax中携带token,并在后台验证。我用的是thinkphp5的框架,用原生php实现也行,多谢赐教
示例代码:
<table id="bt">
<thead>
<tr>
<th data-field="xh" >序号</th>
<th data-field="xm" >姓名</th>
<th data-field="price" >价格</th>
<th data-field="action" >操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>yxg</td>
<td>$1</td>
<td>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-info" onclick="editOne(1);">编辑</button>
<button type="button" class="btn btn-danger" onclick="delOne(1);">删除</button>
</div>
</td>
</tr>
......
js部分
/*ajax 提交封装函数 集成torken */
function sendAjax(vurl,vtype,vdatatype,vdata){
// 设置参数默认值
vtype=vtype||'POST';
vdatatype=vdatatype||'json';
$.ajax({
url: vurl,
type: vtype,
dataType: vdatatype,
data: {'id':vdata},
})
.done(function(data) {
alert(data.msg);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
// 单条编辑
function editOne(id){
var url='edit.php';
var type='POST';
var datatype="json";
var data=id;
sendAjax(url,type,datatype,data);
}
没看出来你准备怎么传 token,一般来说用 cookie 维护的话,每个 http 请求都会带着。如果跨域,ajax 请求里增加
withCredentials
,用 jQuery 的话放到xhrFields
里:文档参考:jQuery.ajax 搜索“xhrFields”。