【问题标题】:json_encode codeigniter pass array to viewjson_encode codeigniter 传递数组来查看
【发布时间】:2018-01-18 09:14:57
【问题描述】:

我想将一个 json 编码的数组传递给 codeigniter 中的视图

public function test() {
    $arr = array(
        "first_name" => "Darian",
        "last_name" => "Brown",
        "age" => "28",
        "email" => "darianbr@example.com"
    );
    echo json_encode($arr);
}

视图中的ajax请求:

$.ajax({
    type: "POST",
    url: "test",
    dataType: 'json',

    success: function (data) {
        alert(data.first_name);
    }
});

【问题讨论】:

  • 在Ajax的响应中只需要数组。我认为不需要渲染视图。

标签: jquery json codeigniter


【解决方案1】:

最好试试这个:

 public function test(){
      $arr = array(
            "first_name" => "Darian",
            "last_name" => "Brown",
            "age" => "28",
            "email" => "darianbr@example.com"
          );
          echo json_encode($arr[0]);
    }

数组从 0 开始。

在你看来:

$.ajax({
  type: "POST",
  url: "test",
  dataType : 'json',
  success :function(data) {
    alert(data);
  }
});

【讨论】:

  • $arr 是关联数组并访问它的索引而不是使用它的键说first_name 会工作吗?
  • 是的,如果你想访问`first_name`,它会。试试看。
【解决方案2】:

问题是 URL,在你的 ajax 请求中,你只引用一个函数,而不是包含该函数的类(控制器)。

现在我正在构建一个使用大量 ajax 请求的应用程序,我这样做的方式就是这样。

$.ajax({
    type: "POST",
    //if u have the js functions on another file (not in your view)
    //u can create a variable on the header like var baseUrl = <?=base_url()?>
    //and url would be like: baseUrl + 'MyController/myFunction'
    url: "<?php echo base_url();?>MyController/myFunction",
    dataType : 'json',
    success :function(data) {
        alert(data.first_name);
    }
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-07-27
    • 2016-03-29
    • 2014-08-07
    相关资源
    最近更新 更多