我正在使用codeigniter 3.1
Ajax帖子无法正常工作,我在控制台中获得了403(Forbidden)。
[POST http://localhost/test/post 403(禁止)]
HTML
<div class="post">
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
</div>
<button id="post">Submit</button>
JAVASCRIPT
$('#post').on('click', function () {
var value1=$("#data1").val();
var value2=$("#data2").val();
$.ajax({
url: window.location.href+'/post',
type: "POST",
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
});
控制器
public function post()
{
$data1 = $this->common->nohtml($this->input->post("data1", true));
$data2 = $this->common->nohtml($this->input->post("data2", true));
$this->data_models->update($this->data->INFO, array(
"data1" => $data1,
"data2" => $data2,
)
);
}
答案 0 :(得分:2)
如果你想要CSRF保护(一个好主意)那么你必须在发布表单数据时传递CSRF令牌 - 通过AJAX或不通过。考虑这种方法。
将令牌放入表单的最简单方法是使用Codeigniter&#34; Form Helper&#34; (Documented here)您可以加载控制器功能或使用自动加载功能。此视图代码假定您已加载帮助程序。
<强> HTML 强>
<div class="post">
<?= form_open('controller_name/post'); //makes form opening HTML tag ?>
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
<?php
echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
echo form_close(); // outputs </form>
?>
</div>
form_open()
函数还会自动将包含CSRF令牌的隐藏字段添加到HTML中。
<强>的Javascript 强>
$('#post').submit(function( event ) {
//the next line will capture your form's fields to a format
//perfect for posting to the server
var postingData = $( this ).serializeArray();
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
data: postingData,
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
<强>控制器强>
当$ _POST到达您的控制器时,CSRF令牌已被条带化,因此您不必担心它&#34;污染&#34;你传入的数据。
public function post()
{
//get all the posted data in one gulp and NO, you do not want to use xss_clean
$posted = $this->input->post();
//With the above the var $posted has this value (showing made up values)
// array("data1" => "whatever was in the field", "data2" => "whatever was in the field");
//sanitize the field data (?)
//just stick the clean data back where it came from
$posted['data1'] = $this->common->nohtml($posted["data1"]);
$posted['data2'] = $this->common->nohtml($posted["data2"]);
$this->data_models->update($this->data->INFO, $posted);
//you must respond to the ajax in some fashion
//this could be one way to indicate success
$response['status'] = 'success';
echo json_encode($response);
}
例如,如果模型函数报告了问题,您还可以发回一些其他状态。然后,您需要在javascript中对该状态做出反应。但是,如果你没有回应,它可能会导致问题。