1

在我的Controller我有一个数组$data,其 var dump 如下:

array
  'urls' =>
    array
      0 =>
        array
          'link_id' => string '1' (length=1)
          'link_name' => string 'http://www.nytimes.com' (length=22)
  'words' =>
    array
      0 =>
        array
          'keyword_id' => string '1' (length=1)
          'keyword' => string 'republican' (length=10)

数组结构:

$ data 将只有urlswords但它们可以有多个值。两者都不会具有相同的基数。

然后我将其编码为echo json_encode($data);indisplayData并将其发送到 ajax。displayData不需要 POST 数据。中发出的ajax请求View如下:

$.ajax({
    url:"http://localhost/codeigniter/SiteController3/displayData",
    success: function(response){
        alert(response);
        $("#user_data").html(response);
    },
    dataType:"json"
})
  • 我想response在我的“视图”中访问,以便我可以执行json_decode($response, true)并获取关联数组。
  • 有一段代码通过在数组上循环以表格格式呈现这些数据。在此代码之前,我想获取关联数组。
  • 我尝试使用$.getJSON而不是$.ajax但没有解决方案。也尝试过$.each功能,但在警报时只得到undefined. 哪个 JSON.stringify警报显示 JSON 但无法将其发送到 PHP 代码。

编辑:

@fragmentedreality 的回答

使用答案解决了内容类型的不一致。但是,我如何访问在 AJAX 成功时收到的响应,其中有一大块用于以表格格式显示数据的 PHP 代码?html bodyView

解决方案:

在下面检查我的答案

4

2 回答 2

1

添加

header('content-type: application/json');

到您的控制器(在 之前echo)为您的应用程序的响应设置正确的 mime 类型。

于 2013-02-21T11:38:28.087 回答
1

最后我放弃了这种JSON方法。displayData我在 的方法中添加了以下行Controller

$this->load->view('data_processing', $data);

The data_processing.php is a new View that generates the HTML table I wanted to display. The response of this View is loaded in my original View by the following AJAX request:

$.ajax
({
    url: "http://localhost/codeigniter/SiteController3/displayData",
}).done(function(data)
    {
         console.log(data);
         $('#user_data').html(data); 
    }
于 2013-02-21T16:58:48.437 回答