鍍金池/ 問答/Java  PHP  C++  HTML/ php ajax提交攜帶token的問題

php ajax提交攜帶token的問題

做項目為了防止crsf攻擊,將編輯和刪除改成了ajax post提交方式,但是不知道怎么在ajax中攜帶token,并在后臺驗證。我用的是thinkphp5的框架,用原生php實現(xiàn)也行,多謝賜教

示例代碼:

<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 提交封裝函數(shù) 集成torken */
        function sendAjax(vurl,vtype,vdatatype,vdata){
            // 設(shè)置參數(shù)默認(rèn)值
            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中,就不用管了,ajax自己會帶上的。
  • 如果不是,header上手動放入token,一下舉例
$.ajax({
????type:"POST",
????url:url,
????data:formData,
????//在請求前設(shè)置請求頭 在請求頭里面設(shè)置設(shè)置請求頭的信息
????beforeSend: function(request) {
????????????request.setRequestHeader("Authorization", token1);
????},
????success:function(res){
????    console.log(res);
????}
});
2018年1月22日 19:58
編輯回答
乖乖瀦

沒看出來你準(zhǔn)備怎么傳 token,一般來說用 cookie 維護(hù)的話,每個 http 請求都會帶著。如果跨域,ajax 請求里增加 withCredentials,用 jQuery 的話放到 xhrFields 里:

$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
});

文檔參考:jQuery.ajax 搜索“xhrFields”。

2018年8月5日 03:59