Returning JSON from PHP to JavaScript?

I have a PHP script that's being called through jQuery AJAX. I want the PHP script to return the data in JSON format to the javascript. Here's the pseudo code in the PHP script:

$json = "{";
foreach($result as $addr)
{
    foreach($addr as $line)
    {
        $json .= $line . "n";
    }
    $json .= "nn";
}
$json .= "}";

Basically, I need the results of the two for loops to be inserted in $json.


Php has an inbuilt JSON Serialising function.

json_encode

json_encode

Please use that if you can and don't suffer Not Invented Here syndrome.


Here are a couple of things missing in the previous answers:

  • Set header in your PHP:

    header('Content-type: application/json');
    echo json_encode($array);
    
  • json_encode() can return a JavaScript array instead of JavaScript object , see:
    Returning JSON from a PHP Script
    This could be important to know in some cases as arrays and objects are not the same.


  • There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.

    As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

    If you don't, here's the PECL library you can install.

    <?php
        $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
    
        echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
    ?>
    
    链接地址: http://www.djcxy.com/p/45824.html

    上一篇: 通过HTTP GET传递多个参数

    下一篇: 从PHP返回JSON到JavaScript?