php - 无法从 PHP 脚本生成的 JSON 数据创建的 JavaScript 对象获取属性

标签 php jquery ajax json codeigniter

我有一个 PHP 脚本,可以对数据库进行查询并将结果作为 JSON 数据返回。该文件包含一些 Codeigniter 特定函数。

该函数接收 id 并将表中的一些数据返回给 JS 代码。

public function get_l($id){
//$id is not empty variable
$this->db->where('id',$id);
$q=$this->db->get('news');

$res = $q->result_array();

$this->output->set_header("HTTP/1.0 200 OK");
$this->output->set_header("HTTP/1.1 200 OK");
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0");
$this->output->set_header("Content-Type: application/json; charset=utf-8");
$this->output->set_header("Pragma: no-cache");

$out = json_encode($res);
$this->output->set_output($out);
}

然后我需要使用下一个 JS 代码处理该 JSON:

function getContent(id){
  $.post('/admin_ajax/news/get',
  {
    id: id

  },
  function(result)
  {
    alert(result+"\n"+result.length);//this will output [object Object] 1
    for (var key in result)
    {
      alert(key+':'+result[key]); //and this 0:[object Object]
    }
    alert(result.title); //here we are getting undefined
  },
  'json'
);

我没有在控制台中收到错误或警告。在 Firebug 中我看到了从服务器返回的内容。

HTTP header :

Server  nginx/1.1.19
Date    Fri, 26 Oct 2012 11:59:12 GMT
Content-Type    application/json; charset=utf-8
Content-Length  85
Connection  keep-alive
X-Powered-By    PHP/5.3.10-1ubuntu3.4
Cache-Control   post-check=0, pre-check=0
Pragma  no-cache

和回应:

[{"id":"5","title":"test","alias":"test","content":"tes","date":"123","type":"test"}]

JSON:

alias  "test"

content "tes"

date  "123"

id "5"

title "test"

type "test"

我发现了类似的问题here但这没有帮助。

最佳答案

您的 JSON 对象位于数组中 [...],因此长度为 1。

function(result) {
    var jsonObj = result[0];

关于php - 无法从 PHP 脚本生成的 JSON 数据创建的 JavaScript 对象获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13086779/

相关文章:

c# - 使用viewModel类-ASP.NET MVC5将数据从 View 发布到 Controller

jquery - Flexslider 具有响应式背景图像

java - 回复 : Joomla/PHP/Java/AJAX

jquery - Django Jquery 可排序 - 如何访问 POST 数据

php - 数据库连接可用于所有类文件

php - 循环生成从今天开始的最后十个星期一

php - 循环不会停止

php - MYSQL数据库插入数据并在网页中显示

javascript - Jquery datepicker 被输入重叠

JavaScript : show load image gif and freeze webpage until xmlhttpRequest responce is received