【问题标题】:Send array with ajax in codeigniter在codeigniter中使用ajax发送数组
【发布时间】:2016-05-14 07:30:28
【问题描述】:

如何使用 ajax 传递数组? 我的代码在视图中:

$(document).ready(function(){

  $('#btn-send').click(function(){

    var value = {
              'name': $('#name').val(),
              'phone': $('#phone').val(),
              'mail': $('#mail').val(),
          };

    $.ajax({
        type: 'POST',
        url: '<?php echo site_url('customer_add/test'); ?>',
        data: value,
        success: function(resp){
            $('#error').html(resp);
        }
    });
  });
});

我的测试方法:

public function test5(){
    $data = $this->input->post["value"];
    $name = $data['name'];
    echo $name; 
}

在 params 中 - 在 inspect 元素中 - 有数据,但作为响应,没有什么可以返回。 怎么了? 提前致谢。

【问题讨论】:

  • 试试这个success : function(data) { //alert("ok"); }, error: function(er){ alert("There is some error"); console.log(er.responseText); }
  • 您在 ajax 中请求函数测试,并且在代码中您向我们展示了服务器脚本中的函数 test5 ???

标签: arrays ajax codeigniter


【解决方案1】:

首先,您可以在$.ajax by error: function(xhr) {}, 的错误部分处理您的错误

$.ajax({
    type: 'POST',
    url: '<?php echo site_url('customer_add/test'); ?>',
    data: {
        name: $('#name').val(),
        phone: $('#phone').val(),
        mail: $('#mail').val()
    },
    error: function(xhr) {
        alert('error');
    },
    success: function(resp){
        $('#error').html(resp);
    }
});

接下来,type: 'POST' 表示表单将通过POST 方法发布字段。
这样我们就可以通过$_REQUEST$_POST 捕获它们。

在 Codeigniter 中,捕获已发布字段的方法是 $this-&gt;input-&gt;post('name');
您的语法有错误。

public function test5(){
    $data['name'] = $this->input->post('name');
    $data['phone'] = $this->input->post('phone');
    $data['mail'] = $this->input->post('mail');

    echo $data;
}

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    您通过 ajax 发送数据,并使用 key:value 对创建一个值数组 使用 post 将数据发送到服务器,这样您就可以获得整个数组 在一个变量中使用。

    public function test5(){
        $data = $this->input->post();
        $name = $data['name']; echo $name;
        $phone = $data['phone']; echo $phone;
        $mail = $data['mail']; echo $mail;
    }
    

    您不必在 $data = $this->input->post["value"]; 中提及 value 键;

    第二件事

    你写错了语法 $this->input->post["value"];

    写入语法是 $this->input->post("value");

    但是在 $this->input->post("value");如果没有带有值名称的键,则无法获取值。

    【讨论】:

    • 谢谢quarksera :) 你是对的。我将其更改为数据:{value:value},现在我得到响应,但问题是这样,表单验证不起作用。起初它返回验证错误,但如果我写入数据,错误仍然相同并且不会改变!
    • 你使用codeignitor表单验证还是自定义给我一些提示,否则我什么都做不了
    猜你喜欢
    • 2020-10-23
    • 2017-01-12
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多