Echo'd PHP encode JSON called via AJAX returns what exactly?

I think something is missing here:

Using AjAX, I get some data from the database and send it back in JSON format $ jsondata = array ();

while ($Row = mysql_fetch_array($params))
{

    $jsondata[]= array('cat_id'=>$Row["cat_id"], 
                          'category'=>$Row["category"], 
                     'category_desc'=>$Row["category_desc"],
                     'cat_bgd_col'=>$Row["cat_bgd_col"]);
};

echo("{\"Categories\": ".json_encode($jsondata)."};");

I don’t think of a problem yet.

On the cleint side, I return the above to

ajaxRequest.responseText

and if I do it

var categoriesObject = ajaxRequest.responseText; 
alert(categoriesObject);

I see what I expect to see, i.e. entire array in warning.

If everything goes wrong, try to access the answer. The error I get is that "categoryObject" is not an object, if not it? that bugginh me that i can't even access it like this:

document.write(categoriesObject.Categories[0].category);

what am I doing wrong?

+5
source share
2 answers
  • JSON . :

    echo json_encode(array('Categories' => $jsondata));
    

    echo json_encode($jsondata);
    

    Categories.

  • JSON , JSON.parse ( , script):

    var data = JSON.parse(ajaxRequest.responseText);
    
  • ,

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

    PHP script.

+11

JSON? .

var categoriesObject = JSON.parse(ajaxRequest.responseText);
+2

All Articles