mko
mko

Reputation: 22104

How to parse list item in html to javascript array

I'm to pass an array form php to javascript, my solution is use php to generate an html list items like following:

<ul id="data" class="hidden">
  <li value="0"> 
    <ul>
      <li value="id">1</li> 
      <li value="productLine">Vintage Cars</li> 
    </ul>
  </li>
  <li value="1"> 
    <ul>
      <li value="id">2</li> 
      <li value="productLine">Ships</li>    
    </ul>
   </li>
   <li value="2"> 
    <ul>
      <li value="id">3</li> 
      <li value="productLine">Trains</li>   
    </ul>
  </li>
</ul>

and use javascript DOM API to make it to an multidimensional associate array:

function selectProductLine(){
    var rootUlNode = document.getElementById('data');
    var rootLiNodes = rootUlNode.children;
    var hiddenHash = {};
    for(var i=0;i< rootLiNodes.length;i++){
        var rootLiNodeValue = rootLiNodes[i].getAttribute('value');     
        var liNodes = rootLiNodes[i].firstElementChild.children;
        for(var i=0; i < liNodes.length;i++){
            hiddenHash[rootLiNodeValue] = {};
            var liNodeValue = liNodes[i].getAttribute('value');
            var liNodeContent = liNodes[i].textContent;
            hiddengegHash[rootLiNodeValue][liNodeValue] = liNodeContent;
        }
    }
return hiddenHash;
}

But running the code can crash my browser, so I can't debug it, anyone can point out where my problem is? And I think there should be an element way to transfer data from php to javascript, like using json, could someone provide a better solution or resource on this topic?

Upvotes: 0

Views: 2574

Answers (3)

Flash
Flash

Reputation: 16743

A better way is to encode the data structure as JSON in PHP, and then call JSON.parse() on the resulting string client-side. You can use json_encode to encode the data and json2.js to parse the string.

Be careful to escape the JSON string appropriately.

Upvotes: 0

simme
simme

Reputation: 1554

Well, your script is ALMOST ok from what I can tell. However you've mispelled hiddenHash 5 lines from the bottom. If I just change hiddengeghash to hiddenhash it runs without errors in jsfiddle atleast. I took the liberty to add a document.write just to make sure it actually returns an array.

http://jsfiddle.net/2WBjJ/

I also changed the second i to i2 since they're used in the same loop

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102783

If you have a PHP array, you can use [json_encode][1] to render it as a JSON object. For example:

<?php
$arr = array(
    array('id' => 1, 'productLine' => 'Vintage Cars'),
    array('id' => 2, 'productLine' => 'Ships')
);
echo 'var products = ' . json_encode($arr) . ';';
?>

Will render like this:

var products = [ { 'id': 1, 'productLine': 'Vintage Cars' }, { 'id': 2, 'productLine': 'Ships' } ];

Upvotes: 1

Related Questions