PHP for Javascript Array (view)

Here in the 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 can I generate this array from php script? I want to use AJAX to get the results returned by php.

Thanks!

EDIT How can I manipulate this php returned by json back in _rowData ?

+1
source share
2 answers

Try using JSON. PHP function json_encode ()

EDIT: Sample code (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 display client-side processing:

 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 a PHP script, you need to make an answer that outputs your array, pre-encoded in JSON format. 2) In addition to YUI, you can also use any appropriate JavaScript library to generate an AJAX request (i.e. JQuery , Prototype ). In my case, I used the eval () function to make an array from a JSON response.

Hope this helps you.

+9
source

Json_encode () example :

 <?php $data = array('name' => 'Imran', 'age' => 23); echo json_encode($data); ?> 

exits

 { 'name': 'Imran', 'age': 23 } 
+3
source

Source: https://habr.com/ru/post/1381695/


All Articles