1

I have a PHP script that makes query to DB and returns the result as JSON data. This file contains some Codeigniter specific functions.

This functions recieve id and returns back to the JS code some data from a table.

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

And then I need to process that JSON with the next JS code:

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

I am not receiving errors or warnings in console. And in the firebug I see what was returned from the server.

HTTP headers:

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

And response:

[{"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"

I found a similar question here but it wasn't helpful.

4

3 に答える 3

3

JSON オブジェクトは配列 [...] にあるため、長さは 1 です。

function(result) {
    var jsonObj = result[0];
于 2012-10-26T12:21:45.123 に答える
1

結果は 1 つの要素を持つ配列です。

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

インデックス 0 の要素には、必要な情報が含まれています。あなたがする必要があります:

alert(result[0].id);
alert(result[0].title);
alert(result[0].alias);
于 2012-10-26T12:20:48.847 に答える
1

It seems like the response you are getting is actually an array with one element (the json object).

Try using result[0], like so:

....
function(result)
  {
    alert(result[0]+"\n"+result[0].length);//this will output [object Object] 1
    for (var key in result[0])
    {
      alert(key+':'+result[0][key]); //and this 0:[object Object]
    }
    alert(result[0].title); //here we are getting undefined
  }
....
于 2012-10-26T12:22:27.887 に答える