简体   繁体   中英

returning multiple values using php to jquery.ajax with json

i'm trying to make a simple call to data from database using php and ajax. I need multiple results. hence i'm using json method. But its not working.

$.ajax({
  type: "POST",
  data: "qid=162",
  url: "activity_ajax.php",
  dataType: json,
  success: function (data) {
    alert(data.first);
  }
});

My activity_ajax.php page returns the following

echo "first":"Steven","last":"Spielberg","address":"1234 Unlisted Drive";

you can send multiple data in an array and then use json_encode

$output =  array('first'=>'Steven',
                 'last'=>'Spielberg',
                 'address'=>'1234 Unlisted Drive');

echo json_encode($output,JSON_FORCE_OBJECT);

and on other side you can access the value by this way

 success : function(resp) {(
              alert(resp.first);
              alert(resp.last);
              alert(resp.address);
            });

Your not returning valid JSON ... change your PHP to this :

$temp = array('first' => 'Steven', 'last' => 'Spielberg', 'address' => '1234 Unlisted Drive');
echo json_encode($temp);

and it will return valid JSON.

The json_encode method returns valid JSON from a variety of sources (an associative array being one)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM