Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - echo'd PHP encode JSON called via AJAX returns what exactly?

I think I'm missing something here:

Using AjAX I get some data from a 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)."};");

No problem so far I think.

On the cleint side I receive back the above into

ajaxRequest.responseText

and if I do this

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

I see what I expect to see ie the entire array in the alert.

Where it all goes wrong is trying to access the response. The error I get is that the "categoriesObject" is not an object - if not what is it? what's bugginh me is that I can't even access it like this:

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

so what am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. You should not create JSON manually. Use:

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

    or just

    echo json_encode($jsondata);
    

    I don't see a reason to add Categories.

  2. You have to decode the JSON on the client side, using JSON.parse (available in most browsers, but also available as script):

    var data = JSON.parse(ajaxRequest.responseText);
    
  3. If you want to be very correct, add

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

    to your PHP script.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...