PHP to Javascript Array (Kind of)
Here in an array i have in javascript, this works great!
_rowData: [
{ name: "Most Recent", view: "recentView" },
{ name: "Most Popular", view: "popularView" },
{ name: "Staff Picks", view: "staffView开发者_如何学运维" }
],
How could i generate this array from a php script? I want to use AJAX to get the results returned by the php.
Thanks!
EDIT
How do i manipulate this php returned json, back into _rowData
?
Try to use JSON. PHP function json_encode()
EDIT: Code example(server side - PHP):
// data handling
$arrayToSend = array(array('name'=>'Most Recent', 'view'=>'recentView'),
array('name'=>'Most Popular', 'view'=>'popularView'),
array('name'=>'Staff Picks', 'view'=>'staffView'));
echo json_encode($arrayToSend);
Client side(javascript). Note: YUI is used to show client-side handling:
var callback = {success: function(req) {
selectItems(req.responseText);
}
};
YAHOO.util.Connect.asyncRequest('GET',url + '?param=1',callback);
function selectItems(resp) {
var result = eval('(' + resp + ')');
for (var i=0; i < result.length; i++) {
// Do whatever you want with array result :)
}
}
Comments: 1) In PHP script you have to make response, which outputs your array, previously encoded to JSON format. 2) Except YUI you can also use any appropriate JavaScript library to generate AJAX request(i.e. JQuery, Prototype). In my case, I used function eval() to make array from JSON response.
Hope, it'll help you.
json_encode() example:
<?php
$data = array('name' => 'Imran', 'age' => 23);
echo json_encode($data);
?>
outputs
{ 'name': 'Imran', 'age': 23 }
精彩评论