gpt4 book ai didi

javascript - Ajax 帖子不工作 codeigniter

转载 作者:行者123 更新时间:2023-12-02 14:03:21 26 4
gpt4 key购买 nike

我使用的是 codeigniter 3.1

Ajax 帖子无法正常工作,我在控制台中收到 403(禁止)。

[发布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+"'}"
});

Controller

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,
)
);

}

最佳答案

如果您希望启用 CSRF 保护(一个好主意),那么您必须在发布表单数据时传递 CSRF token - 通过或不通过 AJAX。考虑这种方法。

将 token 放入表单的最简单方法是使用 Codeigniter 的“表单助手”( Documented here ) 您可以加载 Controller 的函数或使用自动加载。此 View 代码假设您已加载帮助程序。

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 token 的隐藏字段添加到 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);
}
});
});

Controller

当 $_POST 到达您的 Controller 时,CSRF token 已被剥离,因此您不必担心它“污染”您的传入数据。

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 中对该状态使用react。但如果您不回应,可能会导致以后出现问题。

关于javascript - Ajax 帖子不工作 codeigniter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40225908/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com