Ajax发布无法正常工作的Codeigniter [英] Ajax post not working codeigniter

查看:108
本文介绍了Ajax发布无法正常工作的Codeigniter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Codeigniter 3.1

I am using codeigniter 3.1

Ajax发布不起作用,并且我在控制台中收到403(禁止访问).

Ajax post not working and i am getting 403 (Forbidden) in console.

[POST http://localhost/test/post 403(禁止)]

[POST http://localhost/test/post 403 (Forbidden)]

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

  }

推荐答案

如果要启用CSRF保护(一个好主意),则在发布表单数据时必须传递CSRF令牌-是否通过AJAX.考虑这种方法.

If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.

将令牌放入表单的最简单方法是使用Codeigniter的表单帮助器"(在此处记录),您可以加载控制器的功能或使用自动加载功能.此视图代码假定您已加载帮助程序.

The easiest way to put the token in your form is to use Codeigniter's "Form Helper" (Documented here) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.

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.

The form_open() function also automatically adds a hidden field containing the CSRF token to the 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令牌已被剥离,因此您不必担心它会污染"您的传入数据.

By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.

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中对该状态做出反应.但是,如果您不回答,则很可能会导致问题.

You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.

这篇关于Ajax发布无法正常工作的Codeigniter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆