UNDEFINED - PHP与jQuery AJAX的多个返回值

Because I get undefined. Where I am failing?

Code:

    function add(id,cost){
            var info = {
                    "id" : id,
                    "cost": cost,
            };
            $.ajax({
                    data:  info,
                    url:   'a.php',
                    type:  'post',
                    success:  function (datos) {
                             alert(datos+"
 r1: "+datos.r1+"
 r2:"+datos.r2);
                    }
            });
    }

archive a.php PHP:

    $cost=$_POST['id']*$_POST['cost'] + 137;
    echo json_encode(array("r1" =>$_POST['id'], "r2" => $cost));

image

Why do you think $.ajax will understand datos as a JSON? You need to specify it, you can do it using several ways.

Parsing it

    success:  function (datos) {
      datos = JSON.parse(datos);
      alert(datos+"
 r1: "+datos.r1+"
 r2:"+datos.r2);
    }

Specifying in $.ajax itself

$.ajax({
                    data:  info,
                    url:   'a.php',
                    type:  'post',
                    dataType:"json",
      ....

Setting header in PHP (doesn't work for < IE8)

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

I would suggest you to use a combination of first one and third one. Lets not leave any stone unturned.

Datos is probably a string

You can do:

datos = JSON.parse( datos );

Or, you can set the return type to JSON:

$.ajax({
    data:  info,
    dataType: 'json',
    url:   'a.php',
    type:  'post',
    success:  function (datos) {
    alert(datos+"
 r1: "+datos.r1+"
 r2:"+datos.r2);
    }
});